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

Record declaration syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Records help you create simple, immutable data containers easily. They automatically provide useful features like value equality and readable string output.

When you want to store data that should not change after creation, like a person's name and age.
When you need to compare two data objects by their content, not by their location in memory.
When you want a simple way to print or log data objects with clear information.
When you want to create data objects quickly without writing lots of code for properties and methods.
Syntax
C Sharp (C#)
public record RecordName(Type1 Property1, Type2 Property2, ...);
Records are immutable by default, meaning their properties cannot be changed after creation.
You can also declare records with a body to add methods or additional properties.
Examples
This declares a record named Person with two properties: Name and Age.
C Sharp (C#)
public record Person(string Name, int Age);
A simple record to hold coordinates X and Y.
C Sharp (C#)
public record Point(int X, int Y);
This shows a record declared with a body, using init properties for immutability.
C Sharp (C#)
public record Car
{
    public string Make { get; init; }
    public string Model { get; init; }
}
Sample Program

This program creates three Person records. It shows how records print nicely and how equality compares their content.

C Sharp (C#)
using System;

public record Person(string Name, int Age);

class Program
{
    static void Main()
    {
        var person1 = new Person("Alice", 30);
        var person2 = new Person("Alice", 30);
        var person3 = new Person("Bob", 25);

        Console.WriteLine(person1); // Prints the record's data
        Console.WriteLine(person1 == person2); // True because values are equal
        Console.WriteLine(person1 == person3); // False because values differ
    }
}
OutputSuccess
Important Notes

Records provide built-in ToString(), Equals(), and GetHashCode() methods based on their properties.

Use init accessors to keep properties immutable after creation.

Summary

Records are simple, immutable data holders with automatic features.

Use the concise syntax with parentheses to declare properties quickly.

Records compare by value, not by reference, making them great for data equality.