简体   繁体   中英

C# Strange Behavior

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();'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM