← Back to C# Course | Chapter 15: Modern C# Features | Lesson 1 of 6

Records (Immutable Data Types) क्या हैं

एक record जानकारी रखने के लिए एक compact type है जो नहीं बदलती, जैसे एक छपा हुआ name tag। एक जैसे details वाले दो records बराबर माने जाते हैं।
Syntax
csharp
record RecordName(type Property1, type Property2);   // C# 9 immutable data type

var copy = original with { Property1 = newValue };

Records (Immutable Data Types)

C# 9 ने संक्षिप्त, immutable data models के लिए built-in value-based equality वाले record types introduce किए, classes के विपरीत जो reference से compare करती हैं।

चूंकि पूरे record syntax को एक modern Roslyn compiler चाहिए, यह उदाहरण इसके बजाय manually एक class के साथ वही idea बनाता है जो readonly-style properties और एक custom Equals उजागर करती है — वह pattern जिसे कम verbose बनाने के लिए records मौजूद हैं। किसी modern .NET SDK पर, वही model एक line है: record Point(int X, int Y);।

Note: किसी पूरे .NET SDK पर, record Point(int X, int Y); को प्राथमिकता दें — यह constructor, equality, और ToString अपने आप generate करता है।

उदाहरण: Records (Immutable Data Types)

markup
using System;

class Point
{
    public int X { get; }
    public int Y { get; }

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

    public override bool Equals(object obj)
    {
        return obj is Point other && X == other.X && Y == other.Y;
    }

    public override string ToString() => $"Point({X}, {Y})";
}

class Program
{
    static void Main(string[] args)
    {
        Point p1 = new Point(1, 2);
        Point p2 = new Point(1, 2);

        Console.WriteLine(p1);
        Console.WriteLine(p1.Equals(p2));
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी record से mutable होने की उम्मीद करना, जबकि इसकी properties default रूप से init-only हैं।
  2. किसी record का उपयोग करना जब आपको reference identity चाहिए।
  3. एक modified copy बनाने के लिए with expression भूल जाना।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.