Home > Back-end >  The difference between initializing a variable with new() or default?
The difference between initializing a variable with new() or default?

Time:08-11

Code:

using System;

int first = 0;
int second = new();
int third = default;

Console.WriteLine("first: {0};", first);
Console.WriteLine("second: {0};", second);
Console.WriteLine("third: {0};", third);

What is the difference between new(), default and 0 in this context?

CodePudding user response:

For primitive value types (such as integer) the compiler emits identical code for all three cases


    .locals init (
        [0] int32 first,
        [1] int32 second,
        [2] int32 third
   )

// int value = 0;
IL_0000: ldc.i4.0
IL_0001: stloc.0
// int value2 = 0;
IL_0002: ldc.i4.0
IL_0003: stloc.1
// int value3 = 0;
IL_0004: ldc.i4.0
IL_0005: stloc.2

The major difference between default() and new() is for reference types. defaut() is identical to assigning to null, whereas new() calls a constructor

CodePudding user response:

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.

  • Related