Out of curiosity:
This code is valid and executes:
public class Program
{
private static DateTime date;
public static void Main()
{
Console.WriteLine(date.ToString("o"));
}
}
See it working on .NET Fiddle
But this doesn´t even compile (unassigned local variable):
public class Program
{
public static void Main()
{
DateTime date;
Console.WriteLine(date.ToString("o"));
}
}
See it (not) working on .NET Fiddle
DateTime is a non nullable value type, so it doesn´t need to be assigned and initialized to have a value, it has a default one.
So why the compiler allows the DateTime field version compile and doesn´t let the local variable version compile? When the code is compiled to IL, what prevents an value type local variable from being used?
A field that has no explicit initialisation is automatically initialised to the default value.
This is useful as it's a very common initial value, so it saves time.
A local that has no initialisation is in a state where it can not be used.
This is useful because you very likely did something wrong (especially likely if there are several paths that determine the initial value), so just setting it to the default would likely hide a bug.
A local variable is not automatically initialized and thus has no default value. For the purpose of definite assignment checking, a local variable is considered initially unassigned. A local-variable-declaration may include a local-variable-initializer, in which case the variable is considered definitely assigned in its entire scope, except within the expression provided in the local-variable-initializer.
Within the scope of a local variable, it is a compile-time error to refer to that local variable in a textual position that precedes its local-variable-declarator.
Source :- https://msdn.microsoft.com/en-us/library/aa691170(v=vs.71).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With