C# Structs Introduction


This entry is part 5 of 8 in the series C# Complex Types

What is a struct? Structs are programmer-defined data types. They are similar to classes. They have data members and function members. Although structs are similar to classes, there are a number of important differences.

Classes are reference types, and structs are value types. Structs are implicitly sealed, which means they cannot be derived from. Assigning one struct to another copies the values from one to the other. This is quite different from copying from a class variable, where only the reference is copied.

The following code example shows the use of a struct. The following code declares a struct named Point. It has two public fields, named X and Y.

struct Point
{
   public int X;
   public int Y;
}

Structs are value types. Classes are reference types. A variable of a struct type cannot be null. Two struct variables cannot refer to the same object. Consider the following code.

class CSimple
{
   public int X;
   public int Y;
}
struct SSimple
{
   public int X;
   public int Y;
}
class Program
{
   static void Main()
   {
   CSimple cs = new CSimple();
   SSimple ss = new SSimple();
   }
}

Stucts are stored on the stack and classes are stored on the heap.

Series Navigation<< C# Enumerations Part 2C# Structs with Functions >>