In C#, you use the class keyword, a name, and a pair of curly braces to define a new class. The data and methods of the class occur in the body of the class, between the curly braces. Here is a C# class called Circle that contains one method (to calculate the circle's area) and one piece of data (the circle's radius):
class Circle { double Area() { return 3.141592 * radius * radius; } double radius; }
The body of a class contains ordinary methods (such as Area) and fields (such as radius)—remember that variables in a class are called fields. You've already seen how to declare variables in Chapter 2, “Working with Variables, Operators, and Expressions,” and how to write methods in Chapter 3, “Writing Methods and Applying Scope”; in fact, there's almost no new syntax here.
Using the Circle class is similar to using other types that you have already met; you create a variable specifying Circle as its type, and then you initialize the variable with some valid data. Here is an example:
Circle c;// Create a Circle variable c = new Circle();// Initialize it
Note the use of the new keyword. Previously, when you initialized a variable such as an int or a float, you simply assigned it a value:
int i; i = 42;
You cannot do the same with variables of class types. One reason is that C# just doesn't provide the syntax for assigning literal class values to variables. (What is the Circle equivalent of 42?) Another reason concerns the way in which memory for variables of class types is allocated and managed by the common language runtime—this will be discussed further in Chapter 8, “Understanding Values and References.” For now, just accept that the new keyword creates a new instance of a class (more commonly called an object).