Xác định và sử dụng một Class trong C #, bạn sử dụng từ khoá class, tên, và một cặp dấu ngoặc nhọn để định nghĩa một lớp mới. Các dữ liệu và phương pháp của lớp học xảy ra trong cơ thể của lớp, giữa các dấu ngoặc nhọn.
Defining and Using a Class
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):
return 3.141592 * radius * 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:
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
Don't get confused between the terms class and object. A class is the definition of a type.
An object is an instance of that type, created when the program runs. For example, it is
possible to create many instances of the Circle class in a program by using the new
keyword, just as you can create many int variables in a program. Each instance of the
Circle class is an object that occupies its own space in memory, and runs independently
of all the other instances.