Types of constructors
1. Instance Constructor2. Static Constructor (gets called only once)
3. Private Constructor
Static Constructor
A static constructor is used to initialize any static data or to perform a particular action that needs to be performed once automatically before the first instance is created or any static members are referenced.
E.G.
Class SimpleClass
{
static readonly long x;
//static constructor is called at most one time
//before any constructor is invoked or member is accessed
Static SimpleClass()
{
x = DateTime.Now.Ticks;
}
}
Important points to note
- A static constructor does not take access modifier or have parameters
- A static constructor cannot be called directly
- Users have no control only when the static constructor is executed in the program
- A typical use of static constructor is when the class is using a log file and constructor is used to write entries
- We can have both static constructor and instance constructor in same class
Private Constructor
If a class has one or more private constructor *and no public constructor* other class cannot create instance of this class (expect nested class).
We can have both private & public constructor in same class if parameters are different.
By default constructor is private. If we try to create instance of a class having private constructor, you will get constructor is inaccessible due to its protection level
========================================================================
Unless a class is static, class without constructor are given a public default by c# compiler in order to enable class instantiation.
Moral : A class must have public constructor for creating its object
========================================================================
Copy constructor : c# doesn't provide constructor for objects, but we can create
E.g.
class Person
{
//Copy constructor
public Person (Person prevPerson)
{
Name = prevPerson.Name;
Age = prevPerson.Age
}
//Below is parameterized constructor public Person (string name, int age)
{
Person P1 = new Person("George", 40);
Person P2 = new Person (P1);
}
}
No comments:
Post a Comment