Thursday, December 22, 2016

How Default Constructor Works in C#

Whenever a class or struct is created, its constructor will be called. Constructors enables developer to set default values and limit initialization. 

If the constructor is not provided, C# will instantiate default constructor and will assign default values to the member variables. Since value types cannot be null, they will be assign with default values while, Since reference types are null by default they will be assigned with null (Note that regardless of been value or reference type, local variables are not automatically initialized). 

Here .ctor is the shorthand for constructor called in IL (Intermediate Language). As you can see from the above screenshot, you can use free disassembler like ILSpy to view disassembled code.  

If you provide a parameterized constructor, the empty constructor will not be generated.



The purpose of user defining a parameterized constructor is to add some logic when initializing the class, if the compiler automatically adds a empty constructor, users can bypass the some logic in parameterized constructor class. That's why empty constructor is not generated.

Constructor can use base keyword to call the constructor of the base class. (for further details, see Using constructors).

If you try to invoke base default constructor and haven't specified it in the base class you will get 'does not contain a constructor that takes 0 arguments' error.

Static classes can have static constructors to initialize static data. It does not have parameters, and the constructor cannot be called directly. It'll be called automatically. Basically user does not have any control over it. (DotnetPerls)
  
Structs can also have constructors (link2). 

Private constructor is a special type of constructor. It is generally used in classes which contain static members only. Static constructor is used to initialize any static data, or to perform any action which should be performed only once.
Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook