Why can't I define a default constructor for a struct in .NET?

后端 未结 10 2092
时光说笑
时光说笑 2020-11-22 11:04

In .NET, a value type (C# struct) can\'t have a constructor with no parameters. According to this post this is mandated by the CLI specification. What happens i

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 11:35

    A struct is a value type and a value type must have a default value as soon as it is declared.

    MyClass m;
    MyStruct m2;
    

    If you declare two fields as above without instantiating either, then break the debugger, m will be null but m2 will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated!

提交回复
热议问题