Skip to content

Parameterless struct constructors C# 10.0code reduction

Allow structs to have parameterless constructors.

Prior to C# 10.0 a struct could only have constructors that took parameters. Any initialization had to use a static method or a factory method.

Code ​

csharp
public struct Container
{
    public Container()
    {
        Name = "Untitled";
        CreatedAt = DateTime.Now;
    }

    public string Name { get; set; }
    public DateTime CreatedAt { get; set; }
}
csharp
public struct Container
{
    public Container(string name)
    {
        Name = name;
        CreatedAt = DateTime.Now;
    }

    public string Name { get; set; }
    public DateTime CreatedAt { get; set; }
}

Notes ​

  • new Container() and new T() call the constructor, but default, default(T), array elements and unassigned fields are still zero-initialized and skip it
  • Field initializers on structs are also permitted as part of this feature
  • In C# 10 the constructor must still assign every field and auto-property; auto-default structs C# 11.0 removed that requirement

More information ​

Powered by Intracia