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.
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 .
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.
The CLR allows value types to have parameterless constructors, but C# doesn't.
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.
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, ...
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."
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