Language: EN

csharp-structs

What are and how to use structs in C#

A struct in C# is a data structure that represents a set of variables grouped under a single name.

structs are especially useful when working with simple data types that have a predictable size and are primarily used to represent value data.

Structures are value types, which means they can be stored directly on the stack (not on the heap like classes)

Syntax of structs

The basic syntax for defining a structure in C# is as follows:

struct StructureName
{
    // Field definitions
    public DataType Field1;
    public DataType Field2;

    // Method, property definitions, etc.
}
  • StructureName: Is the unique name given to the structure.
  • DataType: Specifies the data type of the fields within the structure.

Basic Example

Below is a basic example of how to define and use a structure in C#:

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public void PrintCoordinates()
    {
        Console.WriteLine($"Coordinates: ({X}, {Y})");
    }
}

// usage
Point point = new Point(3, 5);
point.PrintCoordinates();

Using structs

Declaration and Initialization

Structures are declared and initialized similarly to variables of other data types.

Point point;
point.X = 3;
point.Y = 5;

They can also be initialized if they have a defined constructor.

Point point = new Point(3, 5);

Accessing Fields

Fields of a structure are accessed using dot notation (.).

int x = point.X;

Pass by Value

When a structure is passed as an argument to a method or assigned to another variable, a copy of the value of the structure is passed instead of a reference.

For example, consider the following case,

Point point1 = new Point(3, 5);
Point point2 = point1; // The value of point1 is copied to point2

point2.Y = 10;
// now point1.Y is 5, and point2.Y is 10;

If Point were a class instead of a struct, both point1.Y would have changed to 10. This is because in C#, structs are value types, and classes are reference types.

Practical Examples