Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why struct can not have parameterless constructor [duplicate]

Tags:

c#

Why struct can not have parameterless constructor? What's the problem in doing this for CLR or why it's not allowed ? Please explain it as I don't understand it.

like image 388
Praveen Sharma Avatar asked Feb 22 '09 21:02

Praveen Sharma


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 .

Does struct have default constructor C#?

C# does not allow a struct to declare a default, no-parameters, constructor. The reason for this constraint is to do with the fact that, unlike in C++, a C# struct is associated with value-type semantic and a value-type is not required to have a constructor.

Does C# support Parameterless constructor?

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

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.


2 Answers

I cannot have an explicit parameterless constructor, only the implicit one, that initializes all members to their default.

Although the CLR allows it, C# does not allow structs to have a default parameterless 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. So, even if you happened to define a default constructor, it will not be called and that will only confuse you. To avoid such problems, the C# compiler disallows definition of a default constructor by the user. And because it doesn't generate a default constructor, you can't initialize fields when defining them, ...

like image 149
Rauhotz Avatar answered Oct 11 '22 18:10

Rauhotz


Quite a reasonable explanation can be found at: http://en.csharp-online.net/CSharp_FAQ:_Why_must_struct_constructors_have_at_least_one_argument

Quoting: "The .NET Common Language Runtime (CLR) does not guarantee that parameterless constructors will be called. If structs were permitted to have default, parameterless constructors, the implication would be that default constructors would always be called. Yet, the CLR makes no such guarantee."

like image 27
petr k. Avatar answered Oct 11 '22 17:10

petr k.