I just want explain the concept of static with real world example in a simple way.
Let’s create Student class as below,
- class Student
- {
- public int StudentId
- {
- get;
- set;
- }
- public string StudentName
- {
- get;
- set;
- }
- public string StudentClassName
- {
- get;
- set;
- }
- public string HeadMasterName
- {
- get;
- set;
- }
- }
In the above student class, we have four data members like below, - StudentId - Represent student registration number\
- StudentName - Represent student name
- StudentClassName - Represent student class in which he/she studying
- HeadMasterName - Represent Head Master of the student
We create the individual student by using following function.
- public void getStudentInfo()
- {
- Console.WriteLine("Enter the student details(StudentId,StudentName,StudentClassName,HeadMasterName)");
- StudentId = Convert.ToInt32(Console.ReadLine());
- StudentName = Console.ReadLine().ToString();
- StudentClassName = Console.ReadLine().ToString();
- HeadMasterName = Console.ReadLine().ToString();
- }
Guys, we need to think on a point Head Master, For all students the Head Master is same, so is there any need to enter the Head Master whenever we create student.
No need to enter the Head Master details along with every student, because Head Master is common for all students.
So we enter a Head Master name only once and use for all the students i.e Sharing of the Head Master name among all created student objects, come we will do that as below.
First we make Head Master as “static” by adding static keyword behind data member as below.
- class Student
- {
- public int StudentId
- {
- get;
- set;
- }
- public string StudentName
- {
- get;
- set;
- }
- public string StudentClassName
- {
- get;
- set;
- }
- public static string HeadMasterName
- {
- get;
- set;
- }
- }
Assign the static variable HeadMaster as below,
- public static void Main()
- {
- Student _studentObject = new Student();
- _studentObject.getStudentInfo();
- Student.HeadMasterName = "Hanumanthappa B.K";
- _studentObject.printStudentInfo();
- Console.ReadLine();
- }
By this way we made HeadMaster variable as sharable among all student objects.
Following points to be noticed.
Accessing of static variable with class name not with object name in above example we accessed with class name Student.
If you want to reassign the static variable, you can do it by using class name or in any class function.
Like static variables there is static class, static methods, static constructor.
Conclusion
Static nothing but “SHARING A VARIABLE BETWEEN OBJECTS”.