C# record type

wahidustoz

Wahid Abduhakimov

Posted on March 9, 2022

C# record type

Quyida bir xil vazifani bajaruvchi record va oddiy C# classni ko'ring.

public record OdamRecord(string Ism, string Familya);

public class OdamClass
{
   public OdamClass(string ism, string familya)
   {
      Ism = ism;
      Familya= familya;
   }

   public string Ism{ get; set; }
   public string Familya{ get; set; }
}

var wahidRecord = new PersonRecord("Wahid", "Abduhakimov");
var wahidClass = new PersonClass("Wahid", "Abduhakimov");
Enter fullscreen mode Exit fullscreen mode

1. record immutable(o'zgarmas)

Yuqoridagi usulda record yaratilganda uning property'lari immutable*(o'zgartirib bo'lmas)* bo'ladi. Ularga record yaratilyapkanda qiymat beriladi va keyin o'zgartirishning iloji yo'q. { get; init; } deganday gap.

var wahid = new OdamRecord("Wahid", "Abduhakimov");
wahid.Ism= "David"; // Compile error beradi
Enter fullscreen mode Exit fullscreen mode

2. Tizimli tenglash (==)

record structural equality*(tizimli tenlash)* usulidan foydalanadi. Bu degani agar 2 ta record obyektlarning ichidagi property'lari qiymatlari teng bo'lsa bu ikki obyektlar teng hisoblanadi.

// ... eng tepadagi kodga qarang
var wahid1 = OdamRecord("Wahid", "Abduhakimov");
var wahid2 = OdamRecord("Wahid", "Abduhakimov");
Console.WriteLine($"{wahid1 == wahid2}");          // true

var davron1 = OdamClass("Davron", "Abduhakimov");
var davron2 = OdamClass("Davron", "Abduhakimov");
Console.WriteLine($"{davron1 == davron2}");        // false
Enter fullscreen mode Exit fullscreen mode
  1. record non-immutable record yaratilganda odatda immutable bo'ladi dedik. Lekin uni non-immutable*(o'zgartirsa bo'ladigan)* qilib yaratsa ham bo'ladi.
public record Odam
{
    public string Ism { get; set; }
    public string Familya{ get; set; }
}

var wahid = new Odam("Wahid, "Abduhakimov");
wahid.Ism = "David";  // muammosiz ishlaydi.
Enter fullscreen mode Exit fullscreen mode

Zeriktirib qo'ymaslik uchun davomi keyingi postlarda 😊

Shu joyigacha erinmay o'qib kelgan ekansiz demak siz yoki C#'ni chindan sevasiz yoki shunchaki meni kuzatuvchimsiz. Ikkala holatda ham vaqtingiz uchun katta rahmat 😍

Yurakcha va yakkashoxlarni bosib, menga "podpiska" tashashni unutmang.

Telegram | Instagram

💖 💪 🙅 🚩
wahidustoz
Wahid Abduhakimov

Posted on March 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

C# record type
csharp C# record type

March 9, 2022