- What is the Static Keyword
- When is it Necessary to use the Static Keyword
- Example of Static Method
- What of Static Classes
- Static Constructor
- Summary
What is the Static Keyword
The Static keyword is used to indicate that a member variable belongs to the class itself. When applied to a method, then the method belongs to the class and not to instances of the class. The same applies to properties of a class. Variables or method declared as static are referred to as class variable.
Assuming a class is created with static methods, then we don’t have to create an instance of the class to use the static method.
When is it Necessary to use Static keyword?
Static keyword is used when it is not necessary to create multiple instances of the variable. This means that a single variable exists and can be accessed across multiple instances of the class.
Examples of Static Method
Consider the program below:
class MyGame
{
private int numberOfPlayers;
public static String Status;
public static void GetStatus()
{
Status = “Game Started”;
return Status;
}
}
If we have the code above then in the main program, we can just use the GetStatus() method without having to create an instance of the MyGame class.
So in the main program, we could have something like this:
static void Main(string[] args)
{
String status = MyGame.GetStatus();
}
Here we have called the GetStatus() method directly. This is possible because the GetStatus() method is has been declared as static.
What of Static Classes
A class can also be declared as static. If a class is declared as static, then that class must have only static variables.
If in the above program, we mark the class as static and try to compile, it would generate a compile time error.
static class MyGame
{
private int numberOfPlayers; //there would be error here in this line
public static String Status;
public static void GetStatus()
{
Status = “Game Started”;
return Status;
}
}
{
private static int numberOfPlayers;
public static String Status;
static MyGame()
{
numberOfPlayers = 4;
Status = “Idle”;
}
public static String GetStatus()
{
Status = “Game Started”;
return Status;
}
}
- Static keyword indicates that a method or a variable belongs to a class
- A class can also be marked as static.
- A static method does not need an instance of the class to be called
- If a class is marked as static, then, all the variables and methods should also be marked as static.
- You can have a static constructor in a class which would be used to initialize the static members of the class
