Monday 30 March 2015

What is constructor and types of constructor:-


Hi all,
 This article we discuss what is constructor and how many types of constructor available in c sharp.
What is Constructor?
A constructor is the special method of a class that is called automatically when an object of that class is created. The constructor initializes class parameters and has the same name as the class. It has no return type.
Types of constructors:-
Basically 5 types of constructors available.
These are:-
1:-Default Constructor.
2:-Parameterized constructor.
3:-Copy    constructor(c sharp doesn’t support it)
4:-Static constructor.
5:-Private constructor.
Default Constructor: - A constructor without any parameters is called as default constructor. Drawback of default constructor is every instance of the class will be initialized to same values and it is not possible to initialize each instance of the class to different values.
Parameterized Constructor: - A constructor with at least one parameter is called as parameterized constructor. Advantage of parameterized constructor is you can initialize each instance of the class to different values.
Copy Constructor: - A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance.
Static Constructor: - You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.
Private Constructor : -You can also create a constructor as private. When a class contains at least one private constructor, then it is not possible to create an instance for the class. Private constructor is used to restrict the class from being instantiated when it contains every member as static. 

No comments:

Post a Comment