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?
A struct may declare a parameterless instance constructor. A parameterless instance constructor is valid for all struct kinds including struct , readonly struct , ref struct , and record struct .
Although the CLR allows it, C# does not allow structs to have a default parameter less constructor. The reason is that, for a value type, compilers by default neither generate a default constructor, nor do they generate a call to the default constructor.
A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new . For more information, see Instance Constructors.
The CLR allows value types to have parameterless constructors, but C# doesn't.
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.
The feature was then added back in C# 10.0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With