C# struct new StructType() vs default(StructType)

You might wonder why, if they are exactly the same, there are two ways to do the same thing.

They are not quite the same because every reference type or value type is guaranteed to have a default value but not every reference type is guaranteed to have a parameterless constructor:

static T MakeDefault<T>()
{
    return default(T); // legal
    // return new T(); // illegal
}

UPDATE from 2023: A commenter notes that this answer is out of date; in C# 10, new S() for a struct type S initializes struct fields to their default values, default(S) initializes them to zeros, so there is a difference now. The answer above however still stands; it is not legal to do new T() on a type parameter T unless it is constrained to have a constructor.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)