views:

84

answers:

1

I have a custom struct :

struct A
{
    public int y;
}

a custom class with empty constuctor:

class B
{
    public A a;
    public B()
    {
    }
}

and here is the main:

static void Main(string[] args)
{
    B b = new B();
    b.a.y = 5;//No runtime errors!
    Console.WriteLine(b.a.y);
}


When I run the above program, it does not give me any errors, although I did not initialize struct A in class B constructor..'a=new A();'

+7  A: 

I did not initialize struct A in class B constructor.

C# does this for you. All members of classes are initialized to their default values unless you assign them other values in their declaration or the constructor.

For class instances, the default value is null and you’d get an error when using that instance. However, for struct instances (which are not references unlike class instances), there doesn’t exist a null value. The default value of a struct is an instance where all its fields have been default-initialized.

That’s why your code works.

Konrad Rudolph