C# supports the wild usage of constructors like many other languages. By the way, why it does not support them, although they come into the category of a very fundamental part and the salient features of Object Oriented Programming that provide “instance stability and establishment at the time of creation”. I guess the last sentence isn't self-explanatory for many readers so let's define constructors definitively.
A constructor is a special method of a class that allows the state of an object to be established when the class is created. It is called indirectly when we create an object and keep in mind that the name of the constructor is the same as its class name.
At times you use the default constructor that are already present in the class and you can define it too if you need them and when you use a parameterized constructor to fulfill the requirements of your program there is one more very important and useful type of constructor present, that is the static constructor and I will explore it today in today's article. Moreover a property, a method even an entire class could be static and we will have a complete guide over thus topics too later on, but for now just understand what I am explaining here.
Let's follow the criteria of distributing marks in any of your class test. Let's assume the teacher has announced that this test would be of 20 marks and whoever attends this test will get 5 marks and the remaining 15 marks will depend upon his performance in test and all. So this piece of data should be kept static and in more understanding terms the data field of this class should be set as static, because when you define a non-static or better saying instance-level data then when the object is created each object will have a different independent copy of its own whereas in this case we need to have only a single definition or copy of the pre-assigned 5 marks for just taking the test and that is why we define this field as static, not non-static.
How a static data field with the simple constructor works
Just copy and paste the following code and put a breakpoint where I am indicating and get the concept that I am explaining.
- using System;
-
-
- namespace staicConstructors
- {
- class Test
- {
-
-
- public int obtainedMarks;
-
- public static int fixedMarks;
-
-
- public Test(int obt)
- {
-
- Console.WriteLine("non- static constructor ");
- obtainedMarks = obt;
- fixedMarks=5;
- }
-
- public int SetObtMarks( ){
- return obtainedMarks;
- }
- public int SetFixedMarks()
- {
- return fixedMarks ;
- }
- }
-
-
-
- class Program
- {
- static void Main(string[] args)
- {
-
- Test student1 = new Test(12);
- Test student2 = new Test(11);
- Test student3 = new Test(4);
-
- Console.WriteLine("obtaind marks scored by student1 are "+ student1.SetObtMarks()+"and the fixed marks are"+ student1.SetFixedMarks());
- Console.WriteLine("obtaind marks scored by student2 are "+ student2.SetObtMarks()+ "and the fixed marks are"+ student2.SetFixedMarks());
- Console.WriteLine("obtaind marks scored by student3 are "+ student3.SetObtMarks()+ "and the fixed marks are"+ student3.SetFixedMarks());
- Console.ReadKey();
-
- }
- }
- }
OutputThe purpose of printing a string message is to show that the object is being created. I will definitely do that constructor and execute it for all fields present in its body, regardless of whether it is static or not and by doing this we are ruining and destroying the real purpose and objective of the static data field that I have already described. That is, a static data field needs to be defined and set only once, no matter how many objects will be created and that is why here the concept of static constructor is imprortant.
How a static data field with the static constructor works
Now write the same example with the little difference of a static constructor instead of a non-static constructor.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace staicConstructors
- {
- class Test
- {
-
-
- public int obtainedMarks;
-
- public static int fixedMarks;
-
-
- static Test( )
- {
-
- Console.WriteLine("non- static constructor ");
-
- fixedMarks=5;
- }
- public Test(int mrks)
- {
-
- obtainedMarks = mrks;
- }
-
- public int SetObtMarks( ){
- return obtainedMarks;
- }
- public int SetFixedMarks()
- {
- return fixedMarks ;
- }
- }
-
-
-
- class Program
- {
- static void Main(string[] args)
- {
-
- Test student1 = new Test(12);
- Test student2 = new Test(11);
- Test student3 = new Test(4);
-
- Console.WriteLine("obtaind marks scored by student1 are "+ student1.SetObtMarks()+"and the fixed marks are"+ student1.SetFixedMarks());
- Console.WriteLine("obtaind marks scored by student2 are "+ student2.SetObtMarks()+ "and the fixed marks are"+ student2.SetFixedMarks());
- Console.WriteLine("obtaind marks scored by student3 are "+ student3.SetObtMarks()+ "and the fixed marks are"+ student3.SetFixedMarks());
- Console.ReadKey();
-
- }
- }
- }
TIP
Write ctro inside the class and press the Tab key twice to make the constructor of that class.
Note
I used the line and did a "copy and paste" of the code and ran it. Frankly speaking, though, don't do that, just try to get the basic concept from my code and write every single line of code by yourself. I know this is a very trivial thing to let you note down but these are milestones that will help you to understand coding in the best and easiest way.
OutputNow see, I have defined a static constructor for the static data field “fixed marks” and the purpose of the static data field is to be fulfilled because the static constructor will be called only once to set the value that we need to assigned to all the objects only once, no matter whether there are millions and trillions of objects, all will have the same fixed value for taking the test.
Static constructors have the following prompt attributes to make themselves distinguished from the others:
- A class can have only a single static constructor.
- A static constructor is called before other instance-level constructors present in the class.
- No matter whether you have 2 or even 2 thousands objects in your requirement list the static constructer will be executed only once.
Conclusion
So far we have explained why we need to add another abstraction into the bucket of our concepts and why static constructors are useful to implement in our programs and we have also seen that it is the best practice to use a static constructor to initialize a static data member of our class to get the most of them.