DEV Community

Kudrat
Kudrat

Posted on

Complex types

Struct

Struct kalit so'zi orqali yaratilgan tiplarda bir necha xil ma'lumot saqlasa bo'ladi.

public struct Nuqta
{

}
Enter fullscreen mode Exit fullscreen mode

Structni yuqoridagidek e'lon qilamiz.Bu yerda struct so'zi orqali Nuqta data tipi yaratildi.
Struct o'zining ichida quyidagicha ma'lumotlar saqlashi mumkin.

public struct Nuqta
{
   public X {get; set;}   //property
   public Y {get; set;}   //property

   public void ChopEtish() =>
     Console.WriteLine($"X:{X}, Y:{Y}");  //method
}
Enter fullscreen mode Exit fullscreen mode

Struct bu value type ya'ni o'zgaruvchining ma'lumotlari stackda turadi.Reference typeda o'zgaruvchining o'zi stackda,ma'lumotlari esa Heapda turadi.

Class/Struct ichidagi barcha ma'lumotlar Member deb ataladi.

public struct Nuqta
{   // member
   public X {get; set;}   // auto implemented property
   public Y {get; set;}   

   public int x;      //field

   public void ChopEtish() =>
     Console.WriteLine($"X:{X}, Y:{Y}");  //method
}
Enter fullscreen mode Exit fullscreen mode

Property
Encapsulation-murakkab tiplar ichidagi foydalanuvchiga unchalik qiziq bo'lmagan detallarni yashirish uchun ishlatiladi.

public struct Nuqta
{   
     //encapsulation-yashirish

     private int x = 0; 

     public int GetX() => return x;
     public int SetX(int value) =>x = value;   

}
Enter fullscreen mode Exit fullscreen mode
var a = new Nuqta();
a.Get();
a.Set(10);
Enter fullscreen mode Exit fullscreen mode

Bunaqangi ovoragarchilikni oldini olish maqsadida,propertylarni joriy etishdi.

public struct Nuqta
{   
     //encapsulation-yashirish

     private int x = 0;  //backing field

     public int X        //property
     {
        get => x;
        set => x = value;
     }

     public int Y {get; set;} 
     //auto-implemented property
     //yashirin backing fieldga ega
     //compiler backing field yaratib beradi
}
Enter fullscreen mode Exit fullscreen mode

Shu tarzda propertylar yaratildi.

Constructor
Constructor bu new kalit so'zi orqali obyekt yaratilganda chaqiriladigan funksiya.

var a = new Nuqta();
Enter fullscreen mode Exit fullscreen mode

lekin structureni ichida chaqirilayotgan funskiya mavjud bo'lmaydi.
Vazifalari:

obyekt yaratilganda chaqiriladi
obyekt initialize qilishi uchun ishlatiladi.

Oddiy funksiyalardan farqli o'laroq,constructorlarda return type mavjud emas.Sababi ular hech narsa qaytarmaydi.

Struct/Class ko'rinmas default parametr-less constructorga ega

Class/Struct nomi bilan bir xil bo'ladi
Default constructor public bo'lishi shart

Top comments (0)