0

We are creating a simple struct with a constructor accepting one argument.

public struct test
{
    public int val;

    public test (int a)
    {
        val = a;
    }
}

Yet I notice that the struct can be initialized using the default constructor. Can this be prevented?

test t1 = new test();   //why does this work?
variable
  • 8,262
  • 9
  • 95
  • 215
  • 2
    Not a duplicate any more, now that this is about structs. – O. R. Mapper Mar 29 '14 at 18:36
  • 2
    What you want to achieve is not possible in C# http://stackoverflow.com/questions/535328/hide-parameterless-constructor-on-struct – keyboardP Mar 29 '14 at 18:40
  • There is difference between classes and structs, and this behaviour is one of them. As I do not see any benefits in structs in C#, all my structs are now value objects. To me struct seems to be a feature for familiarizing C/C++ programmers with C#, but has no inherent benefit in this language. – flohack Mar 29 '14 at 19:00

1 Answers1

5

You cannot prevent the usage of the default constructor in C# for value types. A default constructor is required by the C# specification and it is added automatically by the compiler (in fact you cannot define it explicitly). The runtime provides that any value type can be created without calling a constructor to an "all-zero" instance. I'm guessing the C# language designers decided to make that feature of the CLR more explicit by requiring a default parameterless constructor for structs.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
  • Since I was going to include it in my answer, here is the C# spec for a struct: http://msdn.microsoft.com/en-us/library/0taef578.aspx – BradleyDotNET Mar 29 '14 at 18:41
  • Why is it possible for class? – variable Mar 29 '14 at 18:42
  • @NachiketKamat It is possible for classes because the C# language designers made it possible. More importantly, there is no way to initialize a class without calling a constructor in the CLR but there is for structs. – Mike Zboray Mar 29 '14 at 19:01