Hi,
Why the struct cannot have parameterless constructor in c#?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jun 30, 2011, 5:23 AM
This initializes all the struct's fields to their default values (zero for numeric types, false for bool, '\0' for char, null for string and other reference types). For example, this line:
int i = new int();
sets i equal to 0.
Prasant JinagaPosted Jun 30, 2011, 2:47 AM
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.
For instance, an array of value types will be initialized to the initial values of its members—i.e., zero for number type primitive members,
nullfor reference types, and so forth—and not to the values provided in a default constructor. This feature makes structs perform better; because, constructor code need not be called.So, requiring that a constructor contain a minimum of one parameter reduces the possibility that a constructor will be defined which is expected to be called every time the struct type is built.
Thanks,
Prasant
Om prakash SinghPosted Jun 30, 2011, 2:30 AM
Suthish NairPosted Jun 30, 2011, 2:11 AM
Because Struct are value types. The C# doesn't allows value types to have parameterless constructors, but CLR allows. Struct members are automatically initialized to their default values.