SIGN UP MEMBER LOGIN:    
ARTICLE

Constructors in C#

Posted by Puran Mehra Articles | C# Language May 18, 2009
In this article, I will explain the constructor concept in C# along with practical demonstration which will help you to understand it in a simple way.
Reader Level:

Constructors in C-sharp

In this article I will explain the constructor concept in C# along with practical demonstration which will help you to understand it in a simple way.

What is constructor?

  • Constructor is used to initialize an object (instance) of a class.
  • Constructor is a like a method without any return type.
  • Constructor has same name as class name.
  • Constructor follows the access scope (Can be private, protected, public, Internal and external).
  • Constructor can be overloaded.

Constructors generally following types :

  • Default Constructor
  • Parameterized constructor
  • Private Constructor
  • Static Constructor
  • Copy Constructor

The constructor goes out of scope after initializing objects.

Default Constructor

A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.

You need not to define default constructor it is implicitly defined.


Practical: Default Constructor


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
default_constructor
{
class Program
{
class c1
{
int a, b;

public c1()
{
this.a = 10;
this.b = 20;
}

public
void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}", b);
}
}

static
void Main(string[] args)
{
// Here when you create instance of the class default constructor will be called.
c1 ob1 = new c1();
ob1.display();
Console.ReadLine();
}
}
}

Note: In the above practical example if you don't create a constructor still there will be a default constructor, which will initialize the data members of the class with some legal values.

Parameterized constructor


Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.


Practical: Parameterized Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
parameterized_constructor
{
class Program
{
class c1
{
int a, b;

public
c1(int x, int y)
{
this.a = x;
this.b = y;
}

public
void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}", b);
}
}

static
void Main(string[] args)
{
// Here when you create instance of the class parameterized constructor will be called.
c1 ob1 = new c1(10, 20);
ob1.display();
Console.ReadLine();
}
}
}

Private Constructor


Private constructors are used to restrict the instantiation of object using 'new' operator.  A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. 

This type of constructors is mainly used for creating singleton object. If you don't want the class to be inherited we declare its constructor private. We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private. We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.


Practical: Private Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
private_constructor
{
class Program
{

class
c1
{
int a, b;

// Private constructor declared here
private c1(int x, int y)
{
this.a = x;
this.b = y;
}

public
static c1 create_instance()
{
return new c1(12, 20);
}

public
void display()
{
int z = a + b;
Console.WriteLine(z);
}
}

static
void Main(string[] args)
{
// Here the class is initiated using a static method of the class than only you can use private constructor
c1 ob1 = c1.create_instance();
ob1.display();
Console.ReadLine();
}
}
}

Static Constructors


C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster. 

Static constructors are used to initializing class static data members. 

Point to be remembered while creating static constructor: 

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.

Static members are preloaded in the memory. While instance members are post loaded into memory. Static methods can only use static data members.

Practical: Static Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace static_eg
{

class
Program
{

public class test
{
static string name;
static int age;

static
test()
{
Console.WriteLine("Using static constructor to initialize static data members");
name =
"John Sena";
age = 23;
}

public
static void display()
{
Console.WriteLine("Using static function");
Console.WriteLine(name);
Console.WriteLine(age);
}

}

static
void Main(string[] args)
{
test.display();
Console.ReadLine();
}
}
}

Copy Constructor


If you create a new object and want to copy the values from an existing object, you use copy constructor. This constructor takes a single argument: a reference to the object to be copied.

Practical: Copy Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
copy_constructor
{

class
Program
{

class
c1
{
int a, b;

public
c1(int x, int y)
{
this.a = x;
this.b = y;
}

// Copy construtor
public c1(c1 a)
{
this.a = a.a;
this.b = a.b;
}

public
void display()
{
int z = a + b;
Console.WriteLine(z);
}
}

static
void Main(string[] args)
{
c1 ob1 = new c1(10, 20);
ob1.display();
// Here we are using copy constructor. Copy constructor is using the values already defined with ob1
c1 ob2 = new c1(ob1);
ob2.display();
Console.ReadLine();
}
}
}

Copy constructor sets behavior during runtime. It is shallow copying.

I would be glad to share my knowledge and waiting for your feedback to increase my knowledge base.

Summary

In this article, we discussed constructors in C#. Here are some more related articles.



Login to add your contents and source code to this article
share this article :
post comment
 

Hv provided complete constructor package in simpler way

Posted by sandip kolate Oct 09, 2010

Very helpful

Posted by bani noy Oct 03, 2010

Thanks for your Explaination in c# constructor

Posted by periasamy v Sep 29, 2010

this article is easily understanding about constructors

Posted by seetha a Mar 02, 2010


Thanks Douglas,

I will be submitting more article. Need your feedback on them.

Posted by Puran Mehra Jun 29, 2009
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    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.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor