default(MyStruct) vs new MyStruct() - what is the difference?

4/13/2022
2 minute read

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 structs 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 structs. 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().

struct Performance

Let's have a small look into structs and how they work when using Equals and GetHashCode. Plus have a brief look into a new C# 10 feature: readonly record struct.

struct vs readonly struct vs ref struct vs record struct

C# knows struct since its down of time. But there are also recent additions like readonly struct, record struct and ref struct.

This article will show what are the differences between those 4.

C# 12: Default Parameters in Lambdas

There is still a long road ahead of us until the release of .NET 8, but the first new language constructs are getting public. The first one I want to present is: Default Parameters in Lambdas.

An error has occurred. This application may no longer respond until reloaded. Reload x