5

OK, we hear that structcannot have a default parameterless constructor which is fine (http://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net). But documentation says "Each value type has an implicit default constructor that initializes the default value of that type." from http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx

What's the difference between implicit default constructor and parameterless default constructor right now?

3 Answers 3

6

The implicit default constructor is the parameterless constructor which is automatically created by the compiler. The reason you can't create a parameterless constructor is because the default one already exists. I don't know why they chose to do it this way, and why you're not allowed to override it.

Sign up to request clarification or add additional context in comments.

2 Comments

It is the same with class but you can override it :)
As it admits it only really half answers the question.
1

As explained in the answer you point to, using IL, you can define a parameterless constructor for a struct, but there are scenarios where it is not called.

IMHO the "implicit" constructor is just a logical one; implied by the memory being zeroed out when it is allocated.

1 Comment

You can see that answer in my question. I linked it already actually :)
0

Very old question, but to add more to the answer, the implicit constructor is compiled to a different instruction.

Given this C# code:

C c = new();
Console.WriteLine(c);

struct C(int A, int B) { public int a = A; public int b = B; }

the corresponding CIL code is this:

// ...
        IL_0000: ldloca.s 0
        IL_0002: initobj C // <---
        IL_0008: ldloc.0
/// ...

While using the defined constructor uses an entirely different instruction that allocates the needed memory:

// ...
        IL_0000: ldc.i4.1
        IL_0001: ldc.i4.1
        IL_0002: newobj instance void C::.ctor(int32, int32) // <---
// ...

It would seem like initobj does not actually allocate memory (don't quote this though.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.