Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterless constructors in structs for C# 6

Tags:

c#

c#-6.0

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?

like image 211
myfunnyfella Avatar asked Jun 26 '15 00:06

myfunnyfella


People also ask

Can structs have Parameterless constructor?

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 .

Why can struct have Parameterless constructor?

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.

What is a Parameterless 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.

Does C# support Parameterless constructor?

The CLR allows value types to have parameterless constructors, but C# doesn't.


1 Answers

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.

like image 111
svick Avatar answered Sep 22 '22 04:09

svick