Static Constructor:
A static
constructor is used to initialize static data only once, or used to perform
action only once.
It will be
executed only once, unlike the normal constructor that is executed whenever the
object is created.
Syntax:
class SimpleClass
{
// Static constructor
static SimpleClass()
{
//...
}
}
Points to remember:
1. Static Constructor cannot be called directly.
2. No access modifiers allowed with Static
Constructor.
3. Parameters not allowed in Static Constructor.
4. A static constructor is called automatically
to initialize the class before the first instance is created or any static
members are referenced.
5. The user has no control on when the static
constructor is executed in the program.
6. The static constructor for a class executes
before any instance of the class is created.
7. Static constructor executes only one time.
Example:
In following
example constructor EmployeeLeave checks weather current day is working day or week end day. If
current day is Saturday or Sunday constructor sets static field value WorkingDay to false
so Employee is not eligible to apply leave.
public class
EmployeeLeave
{
private
static
bool
isWorkingDay;
public
string
EmployeeID {get;set;}
public
decimal remaningLeaves{get;set;}
public
DateTime FromDate {get;set;}
public
DateTime TodateDate {get;set;}
static
EmployeeLeave()
{
//Getting the Current Date using DateTime Class
DateTime
currentDate = DateTime.Now;
//Checking the Weekend as it is Saturday or
Sunday
if(currentDate.DayOfWeek==DayOfWeek.Saturday||
currentDate.DayOfWeek==DayOfWeek.Sunday)
{
//If the Current Date is Saturday or Sunday
//consider as holiday
isWorkingDay =false;
}
//Days Other than Weekends(i.e other than Staurday
or Sunday)
else
{
//If it is not weekend
//Consider working day
isWorkingDay = true;
}
}
public
void
LeaveApplication()
{
if(isWorkingDay==true)
{
//leave application Code
}
else
{
//Warning message ,tody is saturday or sunday
}
}
}