The Common Type System

There are five types that are defined by the .NET Common Type System (CTS), class, interface, structure, enumeration and delegate.

CTS Class Types

The class is the cornerstone of object oriented programming and can be composed of any number of members (such as constructors, properties, methods and events). Classes are declared using the class keyword, the following is an example:

// A C# class type with 1 method.
class Calc
{
     public int Add(int x, int y)
     {
          return x + y;
     }
}

CTS Interface Types

Interfaces are nothing more than a named collection of abstract member definitions, which may be supported by a given class or structure. By convention, all .NET interfaces begin with a capital letter I, as in the following example:

// A C# interface type is usually
// declared as public, to allow types in other
// assemblies to implement their behavior.
public interface IDraw
{
     void Draw();
}

CTS Structure Types

Structures are basically lightweight class types having value-based semantics. the following is an example of a structure:

// A C# structure type.
struct Point
{
     // Structures can contain fields.
     public int xPos, yPos;

     // Structures can contain parameterized constructors.
     public Point(int x, int y)
     { xPos = x; yPos = y;}

     // Structures may define methods.
     public void PrintPosition()
     {
          Console.WriteLine("({0}, {1})", xPos, yPos);
     }
}

CTS Enumeration Types

Enumerations are a handy programming construct that allow you to group name-value pairs. For example, assume you are creating a video game application that allows the player to select one of three character categories (Wizard, Fighter, or Thief). Rather than keeping track of simple numerical values to represent each possibility, you could build a strongly typed enumeration using the enum keyword.

// A C# enumeration type.
enum CharacterType
{
     Wizard = 100,
     Fighter = 200,
     Thief = 300
}

CTS Delegate Types

Delegates are the .NET equivalent of a type-safe, C-style function pointer. The key difference is that a .NET delegate is a class that derives from System.MulticastDelegate, rather than a simple pointer to a raw memory address. In C#, delegates are declared using the delegate keyword.

// This C# delegate type can "point to" any method
// returning an int and taking two ints as input.
delegate int BinaryOp(int x, int y);

Delegates are critical when you want to provide a way for one object to forward a call to another object and provide the foundation for the .NET event architecture.

Leave a Reply

Your email address will not be published. Required fields are marked *