Share via


Classes (Visual C# Express) 

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.

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.

Static vs. Instance Members

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).

Classes vs. Files

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.

Encapsulation

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 functions 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 functions 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.

Inheritance

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.

Polymorphism

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 Amimal, the calling code can just call the MoveLeft method and the object's own version of the method will be invoked.

Constructors

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();
    }
}

Operator Overloading

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.

Destructors

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).

Structs

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 (Visual C# Express).

See Also

Tasks

How to: Call a Method on an Object (Visual C#)
How to: Inherit From a Class (Visual C#)

Reference

Objects, Classes and Structs (C# Programming Guide)
class (C# Reference)
struct (C# Reference)

Concepts

C# Language Primer (Visual C# Express)