Defining a Class

When you define a class, you describe the characteristics and behavior of objects of that type. In C#, you describe characteristics with member fields:

class Dog
{
   private int weight; // member field
   private string name; // member field
}

Member fields are used to hold each object’s state. For example, the state of the Dog is defined by its current weight and name. The state of an Employee might be defined by (among other things) her current salary, management level, and performance rating. Classes can have instances of other classes as member fields; a Car class might include an Engine class with its own members. Chapter 7 includes a full discussion of member fields.

You define the behavior of your new type with methods. Methods contain code to perform an action:

class Dog
{
   private int weight;
   private string name;

   public void Bark(  )    // member method
   {
   // code here to bark
   }
}

Tip

The keywords public and private are known as access modifiers, which are used to specify what methods of which classes can access particular members. For instance, public members can be called from methods in any class, whereas private members are visible only to the methods of the class defining the member. Thus, objects of any class can call Bark on an instance of Dog, but only methods of the Dog class have access to the weight and name of a Dog. We discuss access modifiers in Chapter 7.

A class typically defines a number of methods to do the work of that class. A Dog class might contain ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.