Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Constructors In C#

Constructors In C#

This article explains constructors in C# with sample examples including constructor overloading, static constructors, and constructor chaining.

Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads :
Total page views :  59773
Rating :
 4/5
This article has been rated :  5 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor



Constructors in C# :

Broadly speaking, it is a method in the class which gets executed when its object is created. Usually we put the initialization code in the constructor. Writing a constructor in the class is pretty simple, have a look at the following sample :
 
public class mySampleClass
{
public mySampleClass()
{
// This is the constructor method.
}
// rest of the class members goes here.
}

When the object of this class is instantiated this constructor will be executed. Something like this :

mySampleClass obj = new mySampleClass()
// At this time the code in the constructor will // be executed


Constructor Overloading :

C# supports overloading of constructors, that means we can have constructors with different set of parameters. So our class can be like this :

public class mySampleClass
{
public mySampleClass()
{
// This is the no parameter constructor method.
// First Constructor
}
public mySampleClass(int Age)
{
// This is the constructor with one parameter.
// Second Constructor
}
public mySampleClass(int Age, string Name)
{
// This is the constructor with two parameters.
// Third Constructor
}
// rest of the class members goes here.
}

Well, note here that call to the constructor now depends on the way you instantiate the object. For example :

mySampleClass obj = new mySampleClass()
// At this time the code of no parameter
// constructor (First Constructor) will be executed
mySampleClass obj = new mySampleClass(12)
// At this time the code of one parameter
// constructor(Second Constructor) will be
// executed.

The call to the constructors is completely governed by the rules of the overloading here.

Calling Constructor from another Constructor:

You can always make the call to one constructor from within the other. Say for example :

public
class mySampleClass
{
public mySampleClass(): this(10)
{
// This is the no parameter constructor method.
// First Constructor
}
public mySampleClass(int Age)
{
// This is the constructor with one parameter.
// Second Constructor
}


Very first of all let us see what is this syntax :    

public mySampleClass(): this(10)

Here this refers to same class, so when we say this(10), we actually mean execute the public mySampleClass(int Age) method.The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.

Another thing which we must know is the execution sequence i.e., which method will be executed when. Here if I instantiate the object as 

mySampleClass obj = new mySampleClass()

Then the code of public mySampleClass(int Age) will be executed before the code of mySampleClass(). So practically the definition of the method : 

public
mySampleClass(): this(10)
{
// This is the no parameter constructor method.
// First Constructor
}

is equivalent to :

public mySampleClass()
{
mySampleClass(10)
// This is the no parameter constructor method.
// First Constructor
}

Note that only this and base (we will see it further) keywords are allowed in initializers, other method calls will raise the error.

This is sometimes called Constructor chaining.

Behavior of Constructors in Inheritance :

Let us first create the inherited class.

public class myBaseClass
{
public myBaseClass()
{
// Code for First Base class Constructor
}
public myBaseClass(int Age)
{
// Code for Second Base class Constructor
}
// Other class members goes here
}
public class myDerivedClass : myBaseClass
// Note that I am inheriting the class here.
{
public myDerivedClass()
{
// Code for the First myDerivedClass Constructor.
}
public myDerivedClass(int Age):base(Age)
{
// Code for the Second myDerivedClass Constructor.
}
// Other class members goes here
}

Now what will be the execution sequence here :

If I create the object of the Derived class as

myDerivedClass obj = new myDerivedClass()

Then the sequence of execution will be 

1. public myBaseClass() method
2. and then public myDerivedClass() method.

Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class.

Note one thing here : We are not making any explicit call to the constructor of base class neither by initializer nor by the base() keyword, but it is still executing. This is the normal behavior of the constructor.

If I create the object of the Derived class as 

myDerivedClass obj =
new myDerivedClass(15)

Then the sequence of execution will be 

1. public myBaseClass(int Age) method.
2. and then public myDerivedClass(int Age) method.

Here the new keyword base has come into picture. This refers to the base class of the current class. So, here it refers to the myBaseClass. And base(10) refers to the call to myBaseClass(int Age) method.

Also note the usage of Age variable in the syntax :

public myDerivedClass(int Age):base(Age).

Understanding it is left to the reader.

Static Constructors :

This is a new concept introduced in C#. By new here I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.

The syntax of writing the static constructors is also damn simple. Here it is :

public class myClass
{
static myClass()
{
// Initialization code goes here.
// Can only access static members here.
}
// Other class methods goes here
}
 

Notes for Static Constructors :

1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Ok fine, all the above points are fine but why is it like that? Let us go step by step here.

Firstly, the call to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it.

Secondly, it is going to be called by CLR, who can pass the parameters to it, if required, No one, so we cannot have parameterized static constructor.

Thirdly, Non-static members in the class are specific to the object instance so static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.

Fourthly, Overloading needs the two methods to be different in terms to methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.

Now, one question raises here, can we have the two constructors as 

public class myClass
{
static myClass()
{
// Initialization code goes here.
// Can only access static members here.
}
public myClass()
{
// Code for the First myDerivedClass Constructor.
}
// Other class methods goes here
}

This is perfectly valid, though doesn't seem to be in accordance with overloading concepts. But why? Because the time of execution of the two method are different. One is at the time of loading the assembly and one is at the time of object creation.

FAQs Regd. Constructors :

1. Is the Constructor mandatory for the class ?

Yes, It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say for example we have the private constructor in the class then it is of no use as it cannot be accessed by the object, so practically it is no available for the object. In such   conditions it will raise an error.

2. What if I do not write the constructor ?

In such case the compiler will try to supply the no parameter constructor for your class behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor ( with or without parameters), then compiler will not make any such attempt.

3. What if I have the constructor public myDerivedClass() but not the public myBaseClass() ? 

It will raise an error. If either the no parameter constructor is absent or it is in-accessible ( say it is private ), it will raise an error. You will have to take the precaution here.

4. Can we access static members from the non-static ( normal ) constructors ?

Yes, We can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
neeraj_saluja
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Good Articlemaha10/6/2007
It is a good article and helpful for beginers in C#. Many thanks for author.
Reply | Email | Delete | Modify | 
Nice Articlekesavan11/19/2007
Thanks
Reply | Email | Delete | Modify | 
STATICNilesh3/9/2008
A detailed description of the word STATIC
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved