C # compiler - initial value of unassigned field and local variable

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"));
    }
}

How it works on .NET Fiddle

But this does not even compile (unassigned local variable):

public class Program
{
    public static void Main()
    {
        DateTime date;
        Console.WriteLine(date.ToString("o"));
    }
}

How it works (not) in .NET Fiddle

DateTime is a type of value that does not allow NULL values, so it does not need to be assigned and initialized to have a value, it has a default value.

So why does the compiler allow you to compile a version of a DateTime field and prevent you from compiling a version of a local variable? When the code compiles to IL, what prevents the use of a local variable of type value?

+5
3

, , .

, , .

, , , .

, , , - ( , , ), .

+3

DateTime - , NULL, , ,

.

docs:

Unlike classes, structures can be created without using an operator new. In this case, there is no constructor call, which makes the distribution more efficient. However, the fields remain unassigned and the object cannot be used until all fields are initialized .

See other answers for "why does the compiler allow compilation of the version of the DateTime field and prevent it from compiling a local variable?"

0
source

Source: https://habr.com/ru/post/1685394/


All Articles