Nondesructive mutation (buzib bo'lmaydigan mutatsiya )

nuriddin321

Nuriddin

Posted on June 5, 2022

Nondesructive mutation (buzib bo'lmaydigan mutatsiya )

C# 10 dan boshlab, struct va recordda new kalit so'zini iwlatmasdan turib obyektyasash imkoniyati paydo bo'ldi. Bunda avval yasalgan obyektdan nusxa olib , agar xoxlasak uni property va fieldlarini o'zgartirib yangi obyekt yasashimiz mumkin. Buning uchun with ifodasidan foydalanishimiz kerak. Quyidagi misolda ko'rsatilganidek, qaysi a'zolarni o'zgartirish va ularning yangi qiymatlarini belgilash uchun ob'ektni ishga tushirish sintaksisidan foydalanamiz:

public record Point
{
    public string Name { get; init; }

    public int Age { get; init; }

    public Point(string name, int age)
    {
        Name = name;
        Age = age;   
    }

    public override string ToString() => $" {Name} , {Age}";

}
Enter fullscreen mode Exit fullscreen mode


    public static void Main()
    { 
        var x1 = new Point("jeki", 22);
        Console.WriteLine(x1);

        var x2 = x1 with{Age = 12};
        Console.WriteLine(x2);

        var x3 = x2 with {Name = "ok",  Age = 33};
        Console.WriteLine(x3);

    }
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
nuriddin321
Nuriddin

Posted on June 5, 2022

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

Sign up to receive the latest update from our blog.

Related