Defining Classes

When you define a new class, you define the characteristics of all objects of that class, as well as their behaviors. For example, if you create your own windowing operating system, you might want to create screen widgets (known as controls in Windows). One control of interest might be a listbox, a control that is very useful for presenting a list of choices to the user and enabling the user to select from the list.

Listboxes have a variety of characteristics: height, width, location, and text color, for example. Programmers have also come to expect certain behaviors of listboxes—they can be opened, closed, sorted, and so on.

Object-oriented programming allows you to create a new type, ListBox, which encapsulates these characteristics and capabilities.

To define a new type or class, you first declare it and then define its methods and fields. You declare a class using the class keyword. The complete syntax is:

[attributes] [access-modifiers] class identifier [:base-class]
{class-body}

Attributes are used to provide special metadata about a class (that is, information about the structure or use of the class). You won’t need to use attributes in this book, but you may run into them if you venture into more advanced topics.

Access modifiers are discussed later in this chapter. (Typically, your classes will use the keyword public as an access modifier.)

The identifier is the name of the class that you provide. Typically, C# classes are named with nouns (Dog, Employee, ListBox ...

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.