Click here to Skip to main content
15,885,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
When you create a class with some fields that don't have any value explicitly specified by the developer they are defaulted to their default values (for Int32 it's zero). So my question is how do they get defaulted? Does the C# compiler do something behind the scenes in the process of compiling? Or maybe it's the runtime?

What I have tried:

I am trying to understand what happens as I am curious to know how the things work under the hood.
Posted
Updated 9-Mar-18 8:45am

Google is your friend:

c# object defaults - Google Search[^]
 
Share this answer
 
Comments
Maciej Los 9-Mar-18 16:00pm    
Oh no! It can't be true! :laugh:
Apart from what John suggested in Solution 1, please also read about value-types and the reference-types in .NET framework context. In the context, if the developer leaves out the initialization step and only performs declaration, the default value is assigned — which is obvious. I am not an expert, but I think this behavior has the roots in C/C++, where, 0 means false and a null pointer was (in very old days) a zero value. So, to make sure everything in the default is same. Like this,

C++
int a = 0;

if(a) {
   // This should not be executed.
} else {
   // Should execute
}

Test this one here, C++ Shell[^]

However, since C# is managed language, it does not let those blocks and always requires an expression that resolves to boolean value if the operand is anything other than boolean.

What I mean to say is, that every object would have something. If the object is reference-type, then it would be null; which is the default value for reference-types like string.

Oh, and C# also supports a default value assignation, too. Like this,
C#
int a = default(int);

// Same as 
int a = new int();
int a = 0;
int a;

These are merely personal choices and preferences. :-)

Default values table (C# Reference) | Microsoft Docs[^]
Value Types and Reference Types | Microsoft Docs[^]

Oh, and yeah, it is the compiler that does all this — if you do not want to really dig deeper inside the CLR and see the IL of the C#. :laugh:
 
Share this answer
 
v2
Comments
BillWoodruff 9-Mar-18 16:48pm    
+5
Afzaal Ahmad Zeeshan 9-Mar-18 16:50pm    
Thanks, Bill.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900