Understanding C# Static Members: Classes, Methods, and More
Written on
Chapter 1: Introduction to Static Members
In C#, the keyword static is utilized to define fields, methods, properties, and classes that can be accessed globally across the application. By declaring these members as static, they become universally available without the need to instantiate the class.
Static Fields
Static fields are accessible throughout the application. They allow for the use of a field without creating an instance of the class. For example:
public class MyClass
{
public static int StaticField = 42;
}
// Accessing the static field
int value = MyClass.StaticField;
Static Methods
Similarly, static methods can be invoked globally without needing to create an instance of the class. Here’s an example:
public class MathUtils
{
public static int Add(int a, int b)
{
return a + b;}
}
// Calling the static method
int result = MathUtils.Add(5, 3);
Static Properties
Static properties are used to provide access to class-level data and can include custom logic for getters and setters. For instance:
public class Configuration
{
private static string _connectionString;
public static string ConnectionString
{
get { return _connectionString; }
set { _connectionString = value; }
}
}
// Accessing and setting the static property
Configuration.ConnectionString = "my_connection_string";
string connectionString = Configuration.ConnectionString;
Static Constructors
A static constructor initializes static data members of a class and is called automatically before any static member is accessed. Here’s how you might define one:
public class MyClass
{
static MyClass()
{
// Initialization code for static members}
}
Static Classes
The static keyword can also define a static class, which cannot be instantiated. For example:
public static class UtilityClass
{
public static void DoSomething()
{
// ...}
}
// Using a method from the static class
UtilityClass.DoSomething();
Chapter 2: Complete Example of Static Members
Here is a comprehensive example demonstrating the use of static members:
using System;
public class Program
{
public static void Main(string[] args)
{
// Accessing static fields
int price = Fruit.FruitPrice;
string name = Fruit.FruitName;
bool isMarket = Fruit.FruitIsInMarket;
// Calling the static method
int result = Fruit.AddFruit(10, 35);
// Accessing and setting the static property
Fruit.FruitSession = "Summer";
string fruitSessionType = Fruit.FruitSession;
// Outputting results
Console.WriteLine("Fruit Name: " + name + " Fruit Price: " + price + " Fruit is Seasonal: " + isMarket);
Console.WriteLine("Fruit Price Sum: " + result);
Console.WriteLine("Fruit Seas