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();’
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
classinstances, the default value isnulland you’d get an error when using that instance. However, forstructinstances (which are not references unlike class instances), there doesn’t exist anullvalue. The default value of astructis an instance where all its fields have been default-initialized.That’s why your code works.