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,
int a = 0;
if(a) {
} else {
}
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,
int a = default(int);
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: