Powered By Blogger

Monday, December 14, 2009

Constructors and Types of Constructors in C#



Constructor:

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

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.

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.

Constructors generally following types :

* Default Constructor
* Parametrized constructor
* Private Constructor
* Static Constructor
* Copy Constructor


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.

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.

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.

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:

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.

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.

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();
}
}

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

The following are the Access Modifiers for constructors,

Public : A constructor that is defined as public will be called whenever a class is instantiated.

Protected : A constructor is defined as protected in such cases where the base class will initialize on its own whenever derived types of it are created.

Private : A constructor is defined as private in such cases whenever a class which contains only static members has to be accessed will avoid the creation of the object for the class.

Internal : An internal constructor can be used to limit concrete implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly.

External : When a constructor is declared using an extern modifier, the constructor is said to be an external constructor.


General:

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

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.

5. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.




Source:

1: http://www.c-sharpcorner.com/UploadFile/neerajsaluja/ConstructorsInCSharp11152005233222PM/ConstructorsInCSharp.aspx

2: http://www.c-sharpcorner.com/UploadFile/cupadhyay/StaticConstructors11092005061428AM/StaticConstructors.aspx

No comments:

Post a Comment