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

后端 未结 5 1445
情深已故
情深已故 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:29

    The language specification (§4.1.2 and §5.2) is your friend. Specifically:

    For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§4.1.2).

    (Italics in original.)

    Note that this is not the same for reference types.

    For a variable of a reference-type, the default value is null.

    This is emphatically different than the value produced by a default constructor, if one exists.

提交回复
热议问题