What is a static member, give three examples of static members of objects that are available to use in C#?
Expert Answer
A static member is a type of member which is created when we don’t want to create its instance. Or we can say that static members are declared for which we don’t want to create its object. We can directly invoke these members by calling their name directly in a C# program without having the need to create their instance/object.
Static Class Members
1) static class
Suppose we need to create a class Department which will everytime return the same specific name and id of the department. Then we will create class department with static keyword appended infront of it.
e.g.
static class Department { public static string GetDepartmentName() { return "Maths"; } public static string GetDepartmentId() { return "Dept01"; } //.. }
Every time the same Department class is used without the need to create any instance of it.
2) static methods
Same is the case with the methods of a particular class declared static. We do not need to instantiate the class to call its methods, just call the respective static methods by using the class name.
e.g: Department.GetDepartmentName();
3) static class variables
Suppose example below.
Class Rectangle{
public static string name;
public static void displayName()
{
name = “Rectangle”;
Consol.WriteLine(name);
}
}
In above example, only one copy of name exists in memory for all the objects of the class created in the program. Hence when we are sure that we no need to change the name and keep the same name for every objects created then we declare a variable static.