What does the keyword static mean | C#
In .NET, the keyword "static" is used to define elements (variables, methods, properties) that belong to the type itself rather than to an instance of the type. When a member is declared as static, it means that the member is associated with the type itself, and not with any specific object instance of that type.
Characteristics and behaviors
Here are the key characteristics and behaviors of static members in .NET:
- Shared Across Instances: Static members are shared among all instances of a class. This means that all instances of the class have access to and share the same static member.
- Accessed Through the Type: Static members are accessed through the type itself, rather than through an instance of the type. They can be accessed using the class name followed by the member name, without needing to create an instance of the class.
- Lifetime: Static members exist for the entire lifetime of the application or until they are explicitly destroyed.
- Memory Allocation: Static members are allocated memory only once, regardless of the number of instances created.
- Global State: Static members can be used to maintain global state or data that needs to be shared across different parts of an application.
Static Variables
class MyClass
{
public static int myStaticVariable;
}
// Accessing the static variable
MyClass.myStaticVariable = 10;
Static Methods
class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
// Calling the static method
int result = Calculator.Add(5, 3);
Static Properties
class Circle
{
private static double _pi = 3.14;
public static double Pi
{
get { return _pi; }
set { _pi = value; }
}
}
// Accessing the static property
double piValue = Circle.Pi;
Conclusion
The "static" keyword in .NET indicates that a member belongs to the type itself rather than to an instance. It allows for shared access and behavior across all instances of a class and can be accessed without creating an instance of the class.
Related Topics
- Difference between a Value Type and a Reference Type
- System level Exceptions Vs Application level Exceptions
- Difference between sub-procedure and function
- What does the term immutable mean
- this.close() Vs Application.Exit()
- Difference between a.Equals(b) and a == b
- Difference between Hashtable and Dictionary
- Difference between Error and Exception
- C# Dictionary Versus List Lookup Time
- Difference between the Class and Interface in C#
- Why does C# doesn't support Multiple inheritance
- How to get the URL of the current page in C# - Asp.Net?