C# -

Readonly Structs

Readonly structs in C# are a special kind of struct that provides better performance and safety by ensuring that the struct's fields are immutable. This tutorial covers everything you need to know about readonly structs, including their definition, benefits, usage, and more.


1. Introduction to Readonly Structs

A readonly struct is a struct that is immutable by design. Once it is initialized, its fields cannot be changed. This immutability can provide performance benefits and make your code safer by preventing unintended modifications.


2. Defining a Readonly Struct

You define a readonly struct by using the readonly keyword before the struct keyword.

Example:
        
            namespace ReadonlyStructExamples;

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

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

3. Benefits of Readonly Structs

Readonly structs offer several benefits, including improved performance, safety, and better design.


4. Usage in Method Parameters

Readonly structs are particularly useful when used as method parameters, as they ensure the data passed to the method cannot be modified.

Example:
        
            namespace ReadonlyStructExamples;

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

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

class Program
{
    static void PrintPoint(Point point)
    {
        Console.WriteLine($"Point: ({point.X}, {point.Y})");
    }

    static void Main(string[] args)
    {
        Point point = new Point(3, 4);
        PrintPoint(point);
    }
}
        
    

5. Usage in Return Types

Using readonly structs as return types ensures that the returned data cannot be modified by the caller.

Example:
        
            namespace ReadonlyStructExamples;

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

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

class Program
{
    static Point CreatePoint(int x, int y)
    {
        return new Point(x, y);
    }

    static void Main(string[] args)
    {
        Point point = CreatePoint(5, 6);
        Console.WriteLine($"Point: ({point.X}, {point.Y})");
    }
}
        
    

6. Performance Considerations

Readonly structs can provide performance benefits, especially in high-performance scenarios where minimizing memory allocation and copying is crucial.


7. Comparison with Classes

While both readonly structs and classes can provide immutability, there are key differences in their behavior and performance characteristics.


8. Thread Safety

Readonly structs can help ensure thread safety by preventing modifications to the struct's state, making them suitable for concurrent applications.


9. Limitations

There are some limitations to using readonly structs, including:


10. Best Practices

When using readonly structs, follow these best practices:


11. Real-World Examples

Let's look at some real-world examples of readonly structs in action.

Point Struct:
        
            namespace ReadonlyStructExamples;

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

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

    public override string ToString()
    {
        return $"({X}, {Y})";
    }
}

class Program
{
    static void Main(string[] args)
    {
        Point point = new Point(3, 4);
        Console.WriteLine(point);
    }
}
        
    
Rectangle Struct:
        
            namespace ReadonlyStructExamples;

public readonly struct Rectangle
{
    public Point TopLeft { get; }
    public Point BottomRight { get; }

    public Rectangle(Point topLeft, Point bottomRight)
    {
        TopLeft = topLeft;
        BottomRight = bottomRight;
    }

    public override string ToString()
    {
        return $"Rectangle [TopLeft: {TopLeft}, BottomRight: {BottomRight}]";
    }
}

class Program
{
    static void Main(string[] args)
    {
        Point topLeft = new Point(0, 0);
        Point bottomRight = new Point(5, 5);
        Rectangle rectangle = new Rectangle(topLeft, bottomRight);
        Console.WriteLine(rectangle);
    }
}
        
    

12. Conclusion

Readonly structs in C# provide a powerful way to create immutable data structures with performance benefits. By understanding their benefits, usage, and limitations, you can make better design choices in your applications.