28
votes

My understanding is that Parameterless constructors in structs are now allowed.

But the following gives me a compile error in VS 2015 Community

public struct Person 
{ 
    public string Name { get; } 
    public int Age { get; } 
    public Person(string name, int age) { Name = name; Age = age; } 
    public Person() : this("Jane Doe", 37) { } 
}

Error: "Structs cannot contain explicit parameterless constructors"

Anyone know why?

2
This link appears to show that it should work in C# 6 with VS 2015: c-sharpcorner.com/UploadFile/0e8478/… Not sure why it is not working for you.Special Sauce
Here is another article with some caveats: volatileread.com/Wiki/Index?id=1091 But nothing to explain your particular issue. Did you check to ensure your project is targeting the .NET 6.0 framework in the Project settings?Special Sauce

2 Answers

44
votes

The feature was present in older previews of C# 6.0, which is why some articles talk about it. But it was then removed and so it's not present in the version distributed with VS 2015 RC.

Specifically, the change was reverted in pull request #1106, with more information about the rationale in issue #1029. Quoting Vladimir Sadov:

As we performed more and more testing, we kept discovering cases where parameterless struct constructors caused inconsistent behavior in libraries or even in some versions of CLR.

[…]

After reconsidering the potential issues arising from breaking long standing assumptions, we decided it was best for our users to restore the requirement on struct constructors to always have formal parameters.

-1
votes

I'm not sure why, however, this is allowed:

public struct Person 
{ 
    public string Name { get; } 
    public int Age { get; } 
    public Person(string name = null, int age = 0) { Name = name; Age = age; } 
}

Does that solve your problem?