Constructor In Depth


Why Constructors?
Initialization of values of different variables is critical in any application development. C# does initialize simple data-types to default values as per the language specification in the .Net framework, but for classes that are user specific, it is obvious that you would be the only one who can decide what is an ideal default value. The means of achieving this is Constructors.


What is a Constructor?
A constructor is a member function that has the same name as the class name and is invoked automatically when the class is instantiated. A constructor is used to provide initialization code that gets executed every time the class is instantiated.

Constructors:
– Constructors cannot be “virtual”.
– They cannot be inherited.
– Constructors are called in the order of inheritance.
– Constructors can be overloaded.
– special function that is called when class is instantiated.
– same name as the class.
– does not have a return type.
– used to initialize values.
– can have parameters.
– compiler will supply one if not declared.

As per the C# specification, a constructor can have the following modifiers.
public
protected
internal
private
extern


How to Use?
* Use application logic in constructors carefully. Try to minimize unnecessary database operations in constructors like loading a Dataset that is used only in specific sections or on demand from the calling class. This is a performance overhead.
* Do not write redundant code in overloaded constructors. This will become a huge maintenance issue as your class hierarchy grows and you start implementing more overloaded constructors in your derived classes. The following example shows a common section where in validation of initialization logic happens.
* Try to use static constructors and variables when you are dealing with Global variables. This is especially a good design practice since you can initialize the static variables easily within static constructors instead of using constant variables. Other advantage would be to encapsulate your instruction logic for these variables.
* Overloaded static constructors are dangerous when used to call other constructors, so try not to call other static constructor from within.
* Design your derived class constructors carefully. This is because when an instance of derived class is created there is more than one constructor that will be called, i.e. both the base class and the derived class in the hierarchy. The constructors of the derived class first will run constructors of base class. The issue arises when you have overloaded constructor definitions in the base and derived classes. Overlooking here would prove costly. Make sure you use the keyword “base()” to make calls to overloaded base classes.

Also note that the constructor initializers “base” and “this” are the only keywords that can be used when making a call to the base constructor, also any one among these can be specified.


There are three types of constructors in C#
a.Instance Constructors
b.Private Constructors
c.Static Constructors

 

a.Instance Constructors
Non-static constructors are also called instance constructors, type constructors, or type initializers, and are used to create and initialize instances of the class they belong to. We can have multiple non-static constructors but only one static constructor for a class. A non-static constructor with no parameters is called the default constructor. If we do not write any constructor for a class, the compiler automatically supplies one. This is the implicit default constructor. This property of C# to supply an implicit default constructor is revoked once we write any constructor for a class.
Non-static constructors can be public, private, protected, external, or internal. A public constructor is one that is called when the class is instantiated. A private constructor is one that prevents the creation of the object of the class. It is commonly used in classes that contain only static members. A class containing an internal constructor cannot be instantiated outside of the assembly. An internal constructor can be used to limit concrete implementations of the abstract class to the assembly defining the class. A protected constructor allows the base class to do its own initialization when subtypes are created. When constructor declaration includes an extern modifier, the constructor is said to be an external constructor. An external constructor declaration provides no actual implementation and hence does not contain any definition. It is to be noted that a public constructor can access a private constructor of the same class through constructor chaining.
Public Constructor Can Access Private Constructor of the Same Class
A protected constructor can only be invoked from the subclasses of the class in which it is defined.

 

b.Private Constructors
Instance constructors are public. If we change the access level of an instance constructor to private or if we haven’t specified any access modifiers at all , it becomes a private constructor
Like methods, default access level of a constructor is private.
It is not possible to inherit a class that has only private constructors.
Uses of private constructors.
**********************
1. Private constructors are commonly used in classes that contain only static
members.This helps to prevent the creation of an instance of a class by other classes when there are no instance fields or methods in that class.
2. Private constructors are useful when you want to create an instance of a class within
a member of the same class and not want to instantiate it out side the class.
3. Private constructors are used to create an instance of a class within a member of a nested class of the same class.

 

c.Static Constructors
A static constructor is used to initialize a class.It is not used to initialize instance of a class.
1. A static constructor must always be parameterless.
2. Since it cannot have parameters,a static constructor cannot be overloaded.
3. Access modifiers are not allowed on static constructors. 
4. A Static constructor cannot be inherited.
5. A static constructor cannot be called explicitly.It is called automatically(implicitly). If a class does not define the entry point Main() method,then the execution of a static constructor is triggered automatically by the first of the following events to occur within an application domain.   
 (Case – A) An instance of the class is created.
 (Case – B) Any of the static members of the class are referenced.
6. If a class contains the entry point Main() method,then the static constructor for that class executes automatically before the Main method is called within an application domain.
7. The static constructor for a class executes at most once in a given application domain.
8. If a class contains any static fields with initializers, those initializers
are executed prior to the execution of static constructor.
9. If a class contains any static fields with out initializers,then those static fields are initialized with default values prior to the execution of static constructor.
See the example of 5
The class AClass of example 5 has a static field ‘aStaticField’. ‘aStaticField’ is not intialized explicitly. So it is automatically intialized with the  default value 0 prior to the execution of static constructor
10. Like static methods, we cannot access a nonstatic field,method or property with in a
static constructor.
11. Static Constructor Executes Before an Instance Constructor
12. Static Constructor Can Access Only Static Members


Constructor Overloading
A constructor can take zero or more arguments as parameters. A constructor with zero arguments is known as the default constructor. We can have multiple constructors in a class with different sets of signatures. Such constructors are known as “overloaded constructors”. The overloaded constructors of a class must differ in their number of arguments, type of arguments, and/or order of arguments. This gives the user the ability to initialize the object in multiple ways.


Constructor Chaining
Constructor chaining refers to the ability of a class to call one constructor from another constructor. In order to call one constructor from another, we use base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether we want to call a constructor in the base class or in the current class.


Constructors and Inheritance
A constructor of a base class is not inherited to its derived class. However, a derived class constructor can call a base class constructor, provided both are non-static.
It is not possible to inherit a class that has only a private constructor.

Advertisements

2 thoughts on “Constructor In Depth

  1. I seldom leave remarks, but i did some searching and wound up here
    Constructor In Depth | Dhondiyals’s Blog.
    And I do ave 2 questions for you if you tend not to mind.
    Could it be only me or does it look like some of these remarks appear aas if they are written by brain dead people?
    😛 And, if you are posting at additional sites, I’d like to keep
    upp with everything new youu have to post. Would you list of all of all your social sites like your linkedin profile, Facebook pasge or twitter feed?

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s