What is static modifier? What are the Static fields and methods?
In C#, the static modifier is used to define members (fields, properties, methods, etc.) that belong to the type itself rather than to a specific instance of the type. When a member is declared as static, it means there is only one copy of that member shared among all instances of the class, and it can be accessed directly through the class name without creating an object instance.
It means you cannot create an instance of a static class. In C# classes, methods, properties, variables, events, operators, constructors can be declared as static by using the static access modifier.
1. Static Fields: Static fields are variables that belong to the class itself rather than any specific object of the class. They are shared among all instances of the class and are initialized only once, at the time of the first access to the class or before the first object of that class is created. Any changes made to the static field will be reflected in all instances of the class.
Example of a static field:
public class MyClass
{
public static int Count = 0;
}
In the above example, 'Count' is a static field of the 'MyClass' class, and it will have the same value across all instances of the class.
2. Static Methods: Static methods are methods that belong to the class itself and not to any particular object of the class. They can be called directly through the class name without creating an instance of the class. Since static methods do not operate on instance-specific data, they often serve utility functions or perform operations that are not dependent on object state.
Example of a static method:
public class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
In this example, 'Add' is a static method of the 'Calculator' class, and it can be called like this: int 'sum = Calculator.Add(5, 3);'.
It's important to note that you cannot access non-static members (fields or methods) directly from within a static method because non-static members require an instance of the class to be accessed. However, you can create an instance of the class within the static method and access the non-static members through that instance.
public class MyClass
{
public int NonStaticValue = 10;
public static void StaticMethod()
{
// Cannot access NonStaticValue directly from here
// Need to create an instance of MyClass to access it
MyClass instance = new MyClass();
int value = instance.NonStaticValue;
}
}
Here's another example to demonstrate that we can access all static members of a class directly using only the class name and the member name, without needing to create an object of the class:
public class Vehicle //class
{
public static string Model { get; set; } //property
public static string Company = "Toyota"; //variable
static Vehicle() //constructor
{
//code here
}
public static string CalculateMileage(int killoMeterTravelled, int Consumpted) //method
{
//some code here
return "";
}
}