Why does the class need a default constructor, but the structure is not needed?

advertisements

Look into following code

public class ABC
{
    public ABC(int a)
    {
    }
}

public struct XYZ
{
    public XYZ(int a)
    {
    }
}

public class Test
{
    //This is invalid.
    ABC _abc = new ABC();

    //This is valid. Why?
    XYZ _xyz = new XYZ();
}

Why struct dont required default constructor where as class required same?


There is always a parameterless constructor in a struct - and you can't define your own one. It will always initialize all fields to their default values. This is effectively a requirement of the CLR, although the CLR itself doesn't refer to this as a constructor, and is described in section 11.3.8 of the C# spec. (Although C# doesn't allow you to declare your own parameterless constructor for structs, the CLR does - and it's sometimes called. See my blog post on the topic for more information.)

The value created by calling the parameterless constructor on a struct is always the same as an "uninitialized" value in an array or an instance/static field.

Classes, however, have a different "default" value, as a field (or array element) of a reference type will be null by default. There is no guaranteed way of creating an instance of a class without specifying any values. If you specify any constructors yourself for a class, the C# compiler will not provide a default constructor, as described in section 10.11.4 of the C# spec.