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

C#
public struct Container
{
    public Container()
    {
        CreatedAt = DateTime.Now;
    }

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

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

Notes

  • default(T) and new T() in generic contexts still use zero-initialization and do not call the parameterless constructor
  • Field initializers on structs are also permitted as part of this feature

More information