DEV Community

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

Posted on

1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay