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

后端 未结 5 1443
情深已故
情深已故 2021-01-31 01:44

Say I have a struct

public struct Foo
{
    ...
}

Is there any difference between

Foo foo = new Foo();

and <

5条回答
  •  鱼传尺愫
    2021-01-31 02:24

    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()
    {
        return default(T); // legal
        // return new T(); // illegal
    }
    

提交回复
热议问题