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 Car
s 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.