How does the constructor set the default value of a class' members?

Viewed 368

According to this link, Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.

class Program
{
    static void Main(string[] args)
    {
        var a = new MyClass();
        Console.WriteLine($"i: {a.i}, b: {a.b}"); //result --> i: 0, b: False
    }
}

public class MyClass
{
    public int i;
    public bool b;
    public MyClass() { }
}

My constructor doesn't have a single line of code. At what point the members of my class get initialized? And what if I don't provide a default constructor but rather a constructor that take some parameters? The documentation doesn't explain that assertion. Do codes similar to this get injected?

public class MyClass
{
    public int i;
    public bool b;
    public MyClass()
    {
        i = default;
        b = default;
    }
}

Thanks for helping

2 Answers

ECMA-334 specification, which defines the C# standard, says this:

10.4.2 - Initially assigned variables

The following categories of variables are classified as initially assigned:

  • Static variables.
  • Instance variables of class instances.
  • Instance variables of initially assigned struct variables.
  • Array elements.
  • Value parameters.
  • Reference parameters.
  • Variables declared in a catch clause or a foreach statement.

So the compiler ensures that these variables are always set to default. This is easily backed up by the CLR, which always initializes all such variable locations (note that local variables are specifically not in the above list).

ECMA-335, which defines the CLR, says:

I.8.11.2 - Field definitions

snip
Fields not marked as static define the representation of a value of a type by defining the substructure of the value (see §I.8.4.1). Locations for such fields are created within every value of the type whenever a new value is constructed. They are initialized during construction of the new value.

When you define a class it is present virtually like blueprint of any design. So When you move to its implementation it becomes reality. Same goes for object and classes in any Object oriented language. When you define class, you basically define blueprint it does not exist yet but when you create object of class, it is created in memory. So in your first case where you have constructor without any arguments when you create object memory space is reserved based on its member and types.

public class MyClass
{
    public int i;
    public bool b;
    public MyClass() { }
 }

In this case when you create object, memory is reserved for int and bool. it does not matter whether you have parameterized constructor where you are assigning values to class members or not. Memory space is reserved with default values for int and bool in heap.

Related