«^»
5.2. Struct types

As well as class types, C# also has struct types. Struct types are declared and used like class types.

Suppose Fred is the following class type:

public class Fred
{
    private int iX;
    private int iY;
    public Fred(int pX, int pY)
    {
        iX = pX;
        iY = pY;
    }
    ...
}
Then, in both Java and C#, an instance of Fred can be created by:

Fred tFredOne = new Fred(100, 200);

This produces:

If we now do:

Fred tFredTwo = tFredOne;

we get:

A declaration of a struct type looks similar to that of a class type:

public struct Bert
{
    private int iX;
    private int iY;
    public Bert(int pX, int pY)
    {
        iX = pX;
        iY = pY;
    }
    ...
}

However, the declaration:

Bert tBertOne = new Bert(100, 200);

produces:

and:

Bert tBertTwo = new Bert(0, 0);

produces:

If we now do:

tBertTwo = tBertOne;

we get:

Like any other local variable (e.g., a local variable of type int), a local variable that is of a struct type comes into being when the block starts and ceases to exist when the block is exited. This is quite different from an object (that is of some class, and is pointed to by some reference variable): the object is created by the use of new and ceases to exist when the garbage collector says so. In implementation terms, a local variable that is of a struct type is allocated on the stack whereas an object is allocated on the heap.

Other points:

  1. It is faster to access a field of a struct than the field of a class.
  2. Passing a struct (as a value parameter) to a method will be slower than passing a value of a class type.
  3. Each struct type is derived from the type object.
  4. A struct type can implement one or more interfaces.
  5. Like class types, a struct type can declare fields, properties, constructors, indexers, methods and operators.
  6. A struct type is sealed meaning that you cannot derive a new type from a struct type.