Constructor(s) in a class is/are special methods which get
called automatically when an object of a class is created. Constructors are
specially used to initialize data members. There are different types of
constructors you can write in a class -
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
class SampleA
{
public SampleA()
{
Console.WriteLine("Sample
A Test Method");
}
}
Default Constructor
When you do not declare any constructor, the class will call its
default constructor which has a default public access modifier. The default
constructor is a parameter less constructor which will be called by a class
object.
Let's see an example of a Default Constructor -
This default constructor will be executed whenever the class is
initialized – Person p = new
Person();
Note: If the class is abstract, then the
accessibility of the default constructor is protected. Otherwise, the
accessibility for the default constructor is public
Parameterized constructors
Now let’s see parameterized constructors. You can also call it
as constructor overloading. Default constructors always initialize the objects
with the same values. In case you want to initialize the class with different
values, you can use Parameterized constructors.
To invoke the parameterized constructor, use this Person p1 = new Person(“DotNet”, “Curry”);
Copy Constructor
Now let's see an example of Copy Constructor. Copy constructor
is the parameterized constructor which takes a parameter of the same type. It
allows you to initialize a new object with the existing object values.
Here’s an example:
|
Static Constructors
Static constructor is used to initialize the static data members
of the class. Static constructor is only called once while creation of the
first instance of the class. After that, no instance of a class will call the
static constructor. You can also use static constructor to execute some code of
the class which must be executed only once.
In inheritance, the calling of the constructor starts from the
parent class.
Let's see how to use these constructors -
It is worth mentioning that you can also create a private constructor,
which is generally used in classes that contain static members only. If
you create a private constructor, you cannot create an instance of a class.
I hope you got an idea of the different types of Constructors in
C#. This question is frequently asked in interviews, so make sure to revise it
before heading for your interview.
No comments:
Post a Comment