You're absolutely right that the value of your three variables is identical when you run this code:
int first = 0;
int second = new();
int third = default;
Console.WriteLine("first: {0};", first);
Console.WriteLine("second: {0};", second);
Console.WriteLine("third: {0};", third);
I get this output:
first: 0;
second: 0;
third: 0;
But let's change that to objects.
object first = 0;
object second = new();
object third = default;
No I get this:
first: 0;
second: System.Object;
third: ;
The first
is 0
, the second
an instance of a object, and the third
is null
.
Three different values.
The reason behind this is for generics. Let's say I have this method:
public T GiveMeTheDefault<T>() => default(T);
Here the compiler will return a new()
for a value type and a null
for a reference type.