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

后端 未结 10 2138
时光说笑
时光说笑 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:42

    What I use is the null-coalescing operator (??) combined with a backing field like this:

    public struct SomeStruct {
      private SomeRefType m_MyRefVariableBackingField;
    
      public SomeRefType MyRefVariable {
        get { return m_MyRefVariableBackingField ?? (m_MyRefVariableBackingField = new SomeRefType()); }
      }
    }
    

    Hope this helps ;)

    Note: the null coalescing assignment is currently a feature proposal for C# 8.0.

提交回复
热议问题