Records (Immutable Data Types) क्या हैं
In this page:
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);।
record Point(int X, int Y); को प्राथमिकता दें — यह constructor, equality, और ToString अपने आप generate करता है।उदाहरण: Records (Immutable Data Types)
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));
}
}
Login to try C/C++/Java/PHP code in the editor
- किसी
recordसे mutable होने की उम्मीद करना, जबकि इसकी properties default रूप से init-only हैं। - किसी
recordका उपयोग करना जब आपको reference identity चाहिए। - एक modified copy बनाने के लिए
withexpression भूल जाना।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: