Home

Generating Static in C# Class Members

|
Updated:  
2018-01-30 12:46:01
|
C# 2010 All-in-One For Dummies
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 author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Bill Sempf is a seasoned programmer and .NET evangelist specializing in .NET applications.

Chuck Sphar is a programmer and former senior technical writer for the Visual C++ product group at Microsoft.