DEV Community

Cover image for The default value to a property ins't really default
Ulisses Cavalcante
Ulisses Cavalcante

Posted on

The default value to a property ins't really default

I was trying to do a simple and easy-to-use validation for a class today, and I came across this situation

First I wrote this class using a property and added there a default value like this public int Age { get; set; } = 18, and I thought already that this property has a default value, and if I compare this instance with default(T), will I have a simple validator?

Code Example

And the answer is NO, I know there are some great projects like Flunt or FluentValidation, but I thought of a simple comparator with the default values, and what I've seen is that actually the =18 is actually just an assignment that occurs during the moment the class is instantiated, but that when declaring the default(T) value it doesn't actually do any attribution declaring only as null.

Code Example

As we can see in previous image, the default(T) return a null value for a reference type like my example class and for a value type this will return 0 value.

For finish this is definition from (docs) [https://docs.microsoft.com/en-us/dotnet/csharp/properties] for an default property.

docs.com definition for properties

if by chance you know any easy way to validate please contribute to the comments below, thanks for reading.

Top comments (0)