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 fields grouped under a single name.

Structures are value types, which means they can be stored directly on the memory stack rather than on the heap like classes.

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

Syntax of structs

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

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

    // Method, property definition, 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();

Use of structs

Declaration and initialization

Structures are declared and initialized in a similar way 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);

Field Access

The fields of a structure are accessed using dot notation (.).

int x = point.X;

Passing by value

When a structure is passed as an argument to a method or assigned to another variable, a copy of the structure’s value 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

Representation of a Point on a Cartesian Plane

In this example, it shows how to define a structure that represents a point on a Cartesian plane.

// Definition of the Point structure
struct Point
{
    public int X; // X coordinate of the point
    public int Y; // Y coordinate of the point

    // Constructor to initialize the point's coordinates
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
}

// Usage
Point point = new Point(3, 4); // Create an instance of the Point structure
Console.WriteLine($"Point: ({point.X}, {point.Y})"); // Print the coordinates of the point

Representation of an RGB Color

In this example, it shows how to define a structure that represents a color in RGB format.

// Definition of the ColorRGB structure
struct ColorRGB
{
    public byte Red; // Red component of the color
    public byte Green; // Green component of the color
    public byte Blue; // Blue component of the color

    // Constructor to initialize the color components
    public ColorRGB(byte red, byte green, byte blue)
    {
        Red = red;
        Green = green;
        Blue = blue;
    }
}

// Usage
ColorRGB color = new ColorRGB(255, 0, 0); // Create an instance of the ColorRGB structure for the color red
Console.WriteLine($"Color RGB: ({color.Red}, {color.Green}, {color.Blue})"); // Print the color components

Representation of a Date

In this example, it shows how to define a structure that represents a date.

// Definition of the Date structure
struct Date
{
    public int Day; // Day of the month
    public int Month; // Month of the year
    public int Year; // Year

    // Constructor to initialize the date
    public Date(int day, int month, int year)
    {
        Day = day;
        Month = month;
        Year = year;
    }
}

// Usage
Date date = new Date(5, 6, 2023); // Create an instance of the Date structure
Console.WriteLine($"Date: {date.Day}/{date.Month}/{date.Year}"); // Print the date

Representation of a Rectangle

In this example, it shows how to define a structure that represents a rectangle.

// Definition of the Rectangle structure
struct Rectangle
{
    public int Width; // Width of the rectangle
    public int Height; // Height of the rectangle

    // Constructor to initialize the rectangle
    public Rectangle(int width, int height)
    {
        Width = width;
        Height = height;
    }

    // Method to calculate the area of the rectangle
    public int CalculateArea()
    {
        return Width * Height;
    }
}

// Usage
Rectangle rectangle = new Rectangle(5, 10); // Create an instance of the Rectangle structure
int area = rectangle.CalculateArea(); // Calculate the area of the rectangle
Console.WriteLine($"Rectangle area: {area}"); // Print the area of the rectangle