In C#, static variables are used when you want a variable to be shared across all instances of a class. They are associated with the type itself rather than with specific instances of the type. Here's a situation where you might use a static variable in a C# class:
Example: Tracking the Number of Instances
Let's say you have a Car class, and you want to track the total number of Car instances created throughout the program's execution. You can achieve this using a static variable to keep count of the instances.
public class Car
{
// Static variable to track the number of instances
private static int numberOfCars = 0;
public string Model { get; set; }
public Car(string model)
{
Model = model;
numberOfCars++; // Increment the count each time a new Car instance is created
}
public static int GetNumberOfCars()
{
return numberOfCars;
}
}
class Program
{
static void Main(string[] args)
{
Car car1 = new Car("Toyota");
Car car2 = new Car("Honda");
Car car3 = new Car("Ford");
Console.WriteLine("Total number of cars: " + Car.GetNumberOfCars()); // Output: 3
}
}
In this example, the numberOfCars variable is static, so it's shared among all instances of the Car class. Each time a new Car instance is created, the count is incremented, allowing you to keep track of the total number of Car instances throughout the program's execution.
No comments:
Post a Comment