Compartir a través de


Classes (C# Programming Guide)

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable. For more information, see Static Classes and Static Class Members (C# Programming Guide).

Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming. For more information, see Inheritance (C# Programming Guide).

Declaring Classes

Classes are declared by 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. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members.

Creating Objects

Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class.

Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:

Customer object1 = new Customer();

When an instance of a class is created, a reference to the object is passed back to the programmer. In the previous example, object1 is a reference to an object that is based on Customer. This reference refers to the new object but does not contain the object data itself. In fact, you can create an object reference without creating an object at all:

Customer object2;

We do not recommend creating object references such as this one that does not refer to an object because trying to access an object through such a reference will fail at run time. However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:

Customer object3 = new Customer();
Customer object4 = object3;

This code creates two object references that both refer to the same object. Therefore, any changes to the object made through object3 will be reflected in subsequent uses of object4. Because objects that are based on classes are referred to by reference, classes are known as reference types.

Class Inheritance

Inheritance is accomplished by using a derivation, which means a class is declared by using a base class from which it inherits data and behavior. A base class is specified by appending a colon and the name of the base class following the derived class name, like this:

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 the members of the base class except the constructors.

Unlike C++, a class in C# can only directly inherit from one base class. However, because a base class may itself inherit from another class, a class may indirectly inherit multiple base classes. Furthermore, a class can directly implement more than one interface. For more information, see Interfaces (C# Programming Guide).

A class can be declared abstract. An abstract class contains abstract methods that have a signature definition but no implementation. Abstract classes cannot be instantiated. They can only be used through derived classes that implement the abstract methods. By constrast, a sealed class does not allow other classes to derive from it. For more information, see Abstract and Sealed Classes and Class Members (C# Programming Guide).

Class definitions can be split between different source files. For more information, see Partial Classes and Methods (C# Programming Guide).

Description

In the following example, a public class that contains a single field, a method, and a special method called a constructor is defined. For more information, see Constructors (C# Programming Guide). The class is then instantiated with the new keyword.

Example

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();
        Console.WriteLine(person1.name);

        person1.SetName("John Smith");
        Console.WriteLine(person1.name);

        // Call the constructor that has one parameter.
        Person person2 = new Person("Sarah Jones");
        Console.WriteLine(person2.name);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output: 
// unknown 
// John Smith 
// Sarah Jones

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

Polymorphism (C# Programming Guide)

Members (C# Programming Guide)

Methods (C# Programming Guide)

Constructors (C# Programming Guide)

Destructors (C# Programming Guide)

Objects (C# Programming Guide)

Concepts

C# Programming Guide

Object-Oriented Programming (C# and Visual Basic)