kind
A "class" is a construct that allows you to combine other types of variables, methods, and events to create your own custom types. A class is like a blueprint that defines the data and behavior of types. If the class is not declared as a static class, the client code can create an "object" or "instance" assigned to the variable, thereby using the class. Until all references to the variable are out of scope, the variable is always kept in memory. When all references are out of scope, the CLR marks the variable for garbage collection. If the class is declared as a static class, there is only one copy in memory and the client code can only access the class through the class itself rather than the "instance variable".
Declaration class
Classes are declared using the class keyword, as shown in the following example:
public class Customer { //Fields, properties, methods and events go here... }
The class keyword is preceded by the access level. Since public is used in this example, anyone can create objects based on that class. The class name is followed by the class keyword. The rest of the definition is the body of the class, used to define behavior and data. The fields, properties, methods, and events of a class are collectively called "class members".
Create an object
Although sometimes classes and objects are interchangeable, they are different concepts. The class defines the type of the object, but it is not the object itself. An object is a concrete entity based on a class, sometimes called an instance of a class.
The object can be created by using the new keyword (subject to the name of the class the object will be based on), as follows:
Customer object1 = new Customer();
After an instance of the class is created, a reference to the object is passed back to the programmer. In the previous example, object1 is a reference to a Customer-based object. This reference refers to the new object, but does not contain the object data itself. In fact, it is possible to create object references without creating objects at all:
Customer object2;
It is recommended not to create object references like this that do not reference objects, because attempts to access objects through such references at runtime will fail. However, you can create a reference object like this by creating a new object, or assigning it to an existing object, as follows:
Customer object3 = new Customer(); Customer object4 = object3;
This code creates two object references that refer to the same object. Therefore, any changes made to the object via object3 will be reflected in object4 that is subsequently used. Since class-based objects are referenced by reference, a class is called a reference type.
Class inheritance
Inheritance is achieved by using "derived", and derivation means that the class is declared using "base class" and its data and behavior are inherited from the base class. By appending a colon and a base class name after the derived class name, you can specify the base class as follows:
public class Manager : Employee { // Employee fields, properties, methods and events are inherited // New Manager fields, properties, methods and events go here... }
When a class declares a base class, it inherits all members of the base class except the constructor.
Unlike C++, classes in C# can only be inherited directly from one base class. However, because the base class itself may also inherit from another class, the class can indirectly inherit multiple base classes. Moreover, a class can directly implement more than one interface.
Classes can be declared as abstract classes. An abstract class contains abstract methods that have signature definitions but not implemented. Abstract classes cannot be instantiated. Abstract classes can only be used by derived classes that implement abstract methods. In contrast, sealed classes do not allow other classes to be derived from them.
Class definitions can be split between different source files.
describe
The following example defines a common class that contains a field, a method, and a special method called a constructor. For more information, see Constructors (C# Programming Guide). Then use the new keyword to instantiate the class.
public class Person { // Field public string name; // Constructor that takes no arguments. public Person() { name = "unknown"; } // Constructor that takes one argument. public Person(string nm) { name = nm; } // Method public void SetName(string newName) { name = newName; } } class TestPerson { static void Main() { // Call the constructor that has no parameters. Person person1 = new Person(); (); ("John Smith"); (); // Call the constructor that has one parameter. Person person2 = new Person("Sarah Jones"); (); // Keep the console window open in debug mode. ("Press any key to exit."); (); } }
Output:
unknown John Smith Sarah Jones
Object
Class or structure definitions act like blueprints, specifying what operations can be performed by this type. Essentially, objects are blocks of memory allocated and configured according to this blueprint. A program can create multiple objects of the same class. Objects, also called instances, can be stored in named variables, or in arrays or collections. The code that uses these variables to call object methods and access object public properties is called client code. In object-oriented languages such as C#, a typical program consists of multiple objects that interact dynamically.
Structural example. . Option class example
Since the class is a reference type, the variable of the class object references the address of the object on the managed heap. If a second object of the same type is assigned to the first object, both variables refer to the object of that address. This will be discussed in more detail later in this topic.
An instance of a class is created using the new operator. In the following example, Person is type, and person1 and person2 are instances of that type (i.e. objects).
public class Person { public string Name { get; set; } public int Age { get; set; } public Person(string name, int age) { Name = name; Age = age; } //Other properties, methods, events... } class Program { static void Main() { Person person1 = new Person("Leopold", 6); ("person1 Name = {0} Age = {1}", , ); // Declare new person, assign person1 to it. Person person2 = person1; //Change the name of person2, and person1 also changes. = "Molly"; = 16; ("person2 Name = {0} Age = {1}", , ); ("person1 Name = {0} Age = {1}", , ); // Keep the console open in debug mode. ("Press any key to exit."); (); } }
Output:
person1 Name = Leopold Age = 6 person2 Name = Molly Age = 16 person1 Name = Molly Age = 16
Since a structure is a value type, the variable of the structure object has a copy of the entire object. An instance of a structure can also be created using the new operator, but this is not required, as shown in the following example:
public struct Person { public string Name; public int Age; public Person(string name, int age) { Name = name; Age = age; } } public class Application { static void Main() { // Create struct instance and initialize by using "new". // Memory is allocated on thread stack. Person p1 = new Person("Alex", 9); ("p1 Name = {0} Age = {1}", , ); // Create new struct object. Note that struct can be initialized // without using "new". Person p2 = p1; // Assign values to p2 members. = "Spencer"; = 7; ("p2 Name = {0} Age = {1}", , ); // p1 values remain unchanged because p2 is copy. ("p1 Name = {0} Age = {1}", , ); // Keep the console open in debug mode. ("Press any key to exit."); (); } }
Output:
p1 Name = Alex Age = 9 p2 Name = Spencer Age = 7 p1 Name = Alex Age = 9
The memory of p1 and p2 is allocated on the thread stack. This memory is recycled with the type or method that declares it. This is one reason why structures are copied when assignment. By contrast, when all references to class instance objects are out of scope, the memory allocated for that class instance is automatically recycled (garbage collection) by the common language runtime. It is impossible to destroy class objects as explicitly as in C++.
Object identification and .value equality
When comparing whether two objects are equal, you must first clarify whether you want to know whether the two variables represent the same object in memory or whether the values of one or more fields of the two objects are equal. If you are comparing values, you must consider whether these two objects are instances of the value type (struct) or instances of the reference type (class, delegate, array).
To determine whether two class instances refer to the same location in memory (meaning they have the same identity), use the static Equals method. (is an implicit base class for all value types and reference types, including user-defined structures and classes.)
To determine whether the instance fields in two structural instances have the same value, use the method. Since all structures are implicitly inherited from , the method can be called directly on the object, as shown in the following example:
// Person is defined in the previous example. //public struct Person //{ // public string Name; // public int Age; // public Person(string name, int age) // { // Name = name; // Age = age; // } //} Person p1 = new Person("Wallace", 75); Person p2; = "Wallace"; = 75; if ((p1)) ("p2 and p1 have the same values.");
Output:
p2 and p1 have the same values.
The implementation of Equals uses reflection because it must be able to determine which fields are in any structure. When creating your own structure, overriding the Equals method can provide algorithms such as efficient findings for your type.