In C# supports various type of constructors. Basically, a constructor is a special method of a class which have the same name as its class name that allows to establish the state of the object or initialize class fields when the class is created. Constructor have some following properties
1. It has the same name of the class.
2. It does not have a return type.
3. It can be private, public or static depend on class type.
4. Constructors can be overloaded by the number and type of parameter.
Here, I discuss about static constructor. According to MSDN, A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced. Static constructors have the following properties:
1. A static constructor does not take access modifiers or have parameters.
3. A static constructor cannot be called directly.
4. The user has no control on when the static constructor is executed in the program.
For use the of Static Constructor have a look at Static constructor
namespace StaticConstructor
{
class Exam
{
public int Eng { get; set; }
public int Hindi { get; set; }
public int Math { get; set; }
public static int Min { get; set; }
public static int Max { get; set; }
public int Total { get; set; }
static Exam() //this call only once during class load.
{
Max = 100;
Min = 35;
Console.WriteLine("Max Mark of each subject {0} and Required Minimum Marks {1} in each Subject ", Max, Min);
}
public Exam(int _eng, int _hin, int _math)
{
Eng = _eng;
Hindi = _hin;
Math = _math;
}
public string getTotal()
{
Total = Eng + Hindi + Math;
if (Eng <= Min || Hindi <= Min || Math <= Min)
{
return "Fail with " + Total.ToString() + " MArks";
}
else
{
return "Pass with " + Total.ToString() + " MArks";
}
}
}
class Program
{
static void Main(string[] args)
{
Exam exam1 = new Exam(58, 56, 85);
Console.WriteLine(exam1.getTotal());
Exam exam2 = new Exam(23, 55, 67);
Console.WriteLine(exam2.getTotal());
Console.Read();
}
}
}
Output is:-
In this example, class Exam
has a static constructor and parameterized Constructor. This class calculates total of the marks obtain in the Subjects (Eng, Hindi & Math) which are properties and have two Static properties Min , Max for minimum & maximum marks When the first instance of Exam
is created (exam1), the static constructor is invoked to initialize the class. The Example output verifies that the static constructor runs only one time, even though two instances (exam1, exam2) of Exam
are created, and that it runs before the instance constructor runs.
Thanks for reading.
;