What is happening and in what order when a new object in being created C#?

Experience Level: Junior
Tags: C#

Answer

When the object is created using 'new' operator, all its property and field values are set to default values first. Then the constructor is executed. The code in the constructor usually assigns some field values and rewrites them by values that the programmer defined. This is called initialization. Once the object gets initialized, its value or reference to its value is returned by the constructor and the caller then further processes the value or reference. Usually it takes it and stores it to a variable.

In the following example, when the code new Radio() gets executed, an instance of class Radio is created. It gets initialized with default values first, so the property VolumeLevel will contain the value 0. Then the constuctor Radio() gets called and it sets the value of VolumeLevel property to 7; The result of evaluating the expression new Radio() a reference to a newly created object of type Radio. This reference then gets stored to the variable myRadio. Later on the property VolumeLevel gets set to 10;

Example
public class Program 
{
  public static void Main() 
  {
    var myRadio = new Radio();
	myRadio.VolumeLevel = 10;
  }
}

  public class Radio 
  {
  public int VolumeLevel { get; set; }
  
  public Radio() 
  {
	VolumeLevel = 7;
  }
}

Comments

No Comments Yet.
Be the first to tell us what you think.
C# for beginners
C# for beginners

Are you learning C# ? Try our test we designed to help you progress faster.

Test yourself