C# 7.0 All-in-One For Dummies
Book image
Explore Book Buy On Amazon
You can generate static in C# class members. Most data members of a class are specific to their containing object, not to any other objects. Consider the Car class:

public class Car

{

public string licensePlate; // The license plate ID

}

Because the license plate ID is an object property, it describes each object of class Car uniquely. For example, your spouse’s car will have a different license plate from your car, as shown here:

Car spouseCar = new Car();

spouseCar.licensePlate = "XYZ123";

Car yourCar = new Car();

yourCar.licensePlate = "ABC789";

However, some properties exist that all cars share. For example, the number of cars built is a property of the class Car but not of any single object. These class properties are flagged in C# with the keyword static:

public class Car

{

public static int numberOfCars; // The number of cars built

public string licensePlate; // The license plate ID

}

Static members aren’t accessed through the object. Instead, you access them by way of the class itself, as this code snippet demonstrates:

// Create a new object of class Car.

Car newCar = new Car();

newCar.licensePlate = "ABC123";

// Now increment the count of cars to reflect the new one.

Car.numberOfCars++;

The object member newCar.licensePlate is accessed through the object newCar, and the class (static) member Car.numberOfCars is accessed through the class Car. All Cars share the same numberOfCars member, so each car contains exactly the same value as all other cars.

Class members are static members. Nonstatic members are specific to each “instance” (each individual object) and are instance members. The italicized phrases you see here are the generic way to refer to these types of members.

About This Article

This article is from the book:

About the book authors:

John Paul Mueller is a writer on programming topics like AWS, Python, Java, HTML, CSS, and JavaScript. William Sempf is a programmer and .NET evangelist. Chuck Sphar was a full-time senior technical writer for the Visual C++ product group at Microsoft.

This article can be found in the category: