Since the beginning of .NET we have the default operator
which basically gives us the default of the given type.
Console.Write(default(int)); // Prints 0
Console.Write(default(DateTime)); // Prints 01/01/0001 00:00:00
Console.Write(default(string)); // Prints nothing as the default of every reference type is null
For Value Types but more specific for struct
s you could also do the same with the new
operator:
Console.Write(new int()); // Prints 0
Console.Write(new DateTime()); // Prints 01/01/0001 00:00:00
Now nothing fancy, unless we will bring C# 10 into the game: C# 10 brought us parameterless constructors and field initializers. So how does the following console output look like?
new MyStruct().PrintToConsole();
default(MyStruct).PrintToConsole();
public struct MyStruct
{
private int anyNumber;
public MyStruct()
{
anyNumber = 10;
}
public void PrintToConsole() => System.Console.WriteLine($"My number is: {anyNumber}");
}
Two "10"s in seperate rows, not? No. The correct output is: 10 and 0. And the reason is simple: default
does not call any constructor when it comes down to struct
s. It doesn't have to do this in the first place. Therefore every field / property will be also initialized with its default values. You can see this in action if you extend the c'tor of our struct with a Console.WriteLine
like this:
var a = new MyStruct();
var b = default(MyStruct);
public struct MyStruct
{
public MyStruct()
{
System.Console.Write("Hey, I was called");
}
}
And only the new MyStruct()
is printing something out. So be aware with C# 10 that default(MyStruct)
is not always the same as new MyStruct()
.