0
0
C Sharp (C#)programming~5 mins

Record structs in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Record structs let you create small, simple data containers that are easy to compare and print. They combine the benefits of structs and records.

When you want a lightweight data type that holds related values together.
When you need value-based equality to compare two data objects easily.
When you want to print or log data objects with a clear, readable format.
When you want to avoid the overhead of classes but still want immutability.
When you want to pass small data around without worrying about references.
Syntax
C Sharp (C#)
public record struct Point(int X, int Y);

This defines a record struct named Point with two properties: X and Y.

Record structs provide built-in methods like ToString(), Equals(), and GetHashCode() based on the data.

Examples
A simple record struct with two integer properties.
C Sharp (C#)
public record struct Point(int X, int Y);
Shows that two record structs with the same data are equal.
C Sharp (C#)
var p1 = new Point(3, 4);
var p2 = new Point(3, 4);
Console.WriteLine(p1 == p2);
Record struct with string and int properties, printing shows property names and values.
C Sharp (C#)
public record struct Person(string Name, int Age);

var person = new Person("Alice", 30);
Console.WriteLine(person);
Sample Program

This program creates three points using a record struct. It prints one point, then compares points for equality.

C Sharp (C#)
using System;

public record struct Point(int X, int Y);

class Program
{
    static void Main()
    {
        var point1 = new Point(5, 10);
        var point2 = new Point(5, 10);
        var point3 = new Point(7, 8);

        Console.WriteLine(point1); // Prints the data nicely
        Console.WriteLine(point1 == point2); // True, same data
        Console.WriteLine(point1 == point3); // False, different data
    }
}
OutputSuccess
Important Notes

Record structs are value types, so they are stored on the stack or inline in other objects.

They automatically provide Equals and GetHashCode based on their data, making comparisons easy.

You can add methods or properties to record structs just like normal structs.

Summary

Record structs combine the simplicity of structs with the helpful features of records.

They make it easy to create small data containers with built-in equality and nice printing.

Use them when you want lightweight, immutable data types with value-based behavior.