logo
Учебник_ПОА

Classes vs. Objects

A class is basically a blueprint for a custom data type. Once you define a class, you use it by loading it into memory. A class that has been loaded into memory is called an object or an instance. You create an instance of a class by using the C# keyword new.

Here is an example of a class definition called SampleClass, and the creation of an object called sampleClass1 that is an instance of that class. Because C# requires that the Main function be defined inside a class, the following code also defines a Program class, but that class is not used to create an object.

using System;

class SampleClass

{

public void SayHello()

{

Console.WriteLine("Hello, World!");

}

}

class Program

{

//Main is the entrypoint, where every C# program starts

static void Main(string[] args)

{

SampleClass sampleClass1 = new SampleClass(); // Create an object

sampleClass1.SayHello(); // Call a method

}

}

Just as you can build any number of houses based on the same blueprint, you can instantiate any number of objects of the same class. It is very common to have arrays or lists that contain many objects of the same class. Each instance of the class occupies a separate memory space and the values of its fields (except its static fields as discussed below) are separate and independent. In the code example below, you could create one object of type Animal and set its size to 2, and another object whose size you set to 3. However, there is an important exception to this rule, and that is the static member.

Классы

C# является объектно-ориентированным языком программирования и аналогично другим современным языкам группирует связанные поля, методы, свойства и события в структуры данных, которые называются классами.