This documentation is archived and is not being maintained.

Classes

Visual Studio 2008

Updated: September 2008

C# is an object-oriented programming language, and in common with other modern languages, it groups related fields, methods, properties, and events into data structures called classes.

A class is basically a blueprint for a custom data type. After you define a class, you can create its objects or instances. You create an instance of a class by using the C# keyword new.

Following is an example of a class named SampleClass, and the creation of an object named sampleClass1 that is an instance of that class.

The following code also defines a Program class that contains the Main method. This method is the first method invoked in any C# console or Windows Forms application. Although the Main method must be declared in the class, no class instance is created to call this method.

using System;

class SampleClass
{
    public void SayHello()
    {
        Console.WriteLine("Hello, World!");
    }
}

class Program
{
    // Main is the entry point, where every C# program starts. 
    static void Main(string[] args)
    {
        // Create an object.
        SampleClass sampleClass1 = new SampleClass();
        // Call a method.
        sampleClass1.SayHello();                       
    }
}

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.

A static member is a method or field that can be accessed without reference to a particular instance of a class. The most common static method is Main, which is the entry point for all C# programs; note that you do not need to create an instance of the containing class in order to call the Main method. Another commonly used static method is WriteLine in the Console class. Note the difference in syntax when accessing static methods; you use the class name, not the instance name, on the left side of the dot operator: Console.WriteLine.

When you declare a class field static, all instances of that class will "share" that field. If size in the following code example were declared static, and one Animal object changed the value, the value would be changed for all objects of type Animal.

A static class is one whose members are all static. Static classes, methods and fields are useful in certain scenarios for performance and efficiency reasons. However, subtle errors can arise if you assume that a field is an instance field when in fact it is static. For more information, see Static Classes and Static Class Members (C# Programming Guide).

Every C# program has at least one class. When designing your program, it is good practice, but not a requirement, to keep a single class in each source code (.cs) file. If you use the C# integrated development environment (IDE) to create classes, it will automatically create a new source code file for you at the same time.

A class typically represents the characteristics of a thing, and the actions that it can perform. For example, to represent an animal as a C# class, you might give it a size, speed, and strength represented as numbers, and some methods such as MoveLeft(), MoveRight(), SpeedUp(), Stop() and so on, in which you would write the code to make your "animal" perform those actions. In C#, your animal class would look like this:

    public class Animal
    {
        private int size;
        private float speed;
        private int strength;

	    public void MoveLeft()  // method
	    {
		    // code goes here...
        }

        // other methods go here...
    }

If you browse through the .NET Framework Class Library, you will see that each class represents a "thing," such as an XmlDocument, a String, a Form, and that each thing has various actions that it can perform (methods), characteristics that you can read and perhaps modify (properties) and notifications (events) that it sends out when it performs some given action. The methods, properties and events, along with all the other internal variables and constants (fields), are referred to as the members of the class.

Grouping members together into classes is not only logical, it also enables you to hide data and methods that you do not want other code to have access to. This principle is known as encapsulation. When you browse the .NET Framework class libraries, you are seeing only the public members of those classes. Each class probably also has private members that are used internally by that class or classes related to it, but are not meant to be used by applications. When you create your own classes, you will decide which members should be public, and which should be private.

A class can inherit another class, which means that it includes all the members, public and private, of the original class, plus the additional members that it defines. The original class is called the base class and the new class is called the derived class. You create a derived class to represent something that is a more specialized kind of the base class. For example, you could define a class Cat that inherits from Animal. A Cat can do everything an Animal can do, plus it can perform one additional unique action. The C# code looks like this:

    public class Cat : Animal
    {
	    public void Purr()
	    {
	    }
    }

The Cat : Animal notation indicates that Cat inherits from Animal and that therefore Cat also has a MoveLeft method and the three private variables size, speed, and strength. If you define a SiameseCat class that inherits from Cat, it will have all the members of Cat plus all the members of Animal.

In the field of computer programming, polymorphism refers to the ability of a derived class to redefine, or override, methods that it inherits from a base class. You do this when you need to do something specific in a method that is either different or else not defined in the base class. For example, the Animal.MoveLeft method, since it must be very general in order to be valid for all animals, is probably very simple: something like "change orientation so that animal's head is now pointing in direction X". However, in your Cat class, this might not be sufficient. You might need to specify how the Cat moves its paws and tail while it turns. And if you have also defined a Fish class or a Bird class, you will probably need to override the MoveLeft method in different ways for each of those classes also. Because you can customize the behavior of the MoveLeft method for your particular class, the code that creates your class and calls its methods does not have a separate method for each animal in the world. As long as the object inherits from Animal, the calling code can just call the MoveLeft method and the object's own version of the method will be invoked.

Every class has a constructor: a method that shares the same name as the class. The constructor is called when an object is created based on the class definition. Constructors typically set the initial values of variables defined in the class. This is not necessary if the initial values are to be zero for numeric data types, false for Boolean data types, or null for reference types, as these data types are initialized automatically.

You can define constructors with any number of parameters. Constructors that do not have parameters are called default constructors. The following example defines a class with a default constructor and a constructor that takes a string, and then uses each:

class SampleClass
{
    string greeting;

    public SampleClass()
    {
        greeting = "Hello, World";
    }

    public SampleClass(string message)
    {
        greeting = message;
    }

    public void SayHello()
    {
        System.Console.WriteLine(greeting);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Use default constructor.
        SampleClass sampleClass1 = new SampleClass();
        sampleClass1.SayHello();

        // Use constructor that takes a string parameter.
        SampleClass sampleClass2 = new SampleClass("Hello, Mars");
        sampleClass2.SayHello();
    }
}

Creating different methods with the same name, in the previous example SampleClass(), is called overloading. The compiler knows which method to use because the list of arguments, if there are any, is provided each time an object is created. Overloading can make your code more flexible and readable.

You may already know about destructors if you have used C++. Because of the automatic garbage collection system in C#, it is not likely that you will ever have to implement a destructor unless your class uses unmanaged resources. For more information, see Destructors (C# Programming Guide).

A struct is a kind of type that is similar to a class in many ways except that it does not support inheritance. For more information, see Structs.

Date

History

Reason

September 2008

Updated information about Main method.

Customer feedback.

Show: