params key-word

params – kalit so’zi avvalroq c# ning 12-chi versiyasida taqdim etilgan edi, u vaqtda params ni faqat array turiga nisbatan ishlata olardik, 13-chi versiyada esa params harqanday collection turiga nisbatan ishlatsa bo’ladi, yani harqanday IEnumerable vorislariga qollasa boladi.
params kalit so’zi o’zgaruvchan sonli(istalgan miqtorda), argumentlarni metodga o’tkazish imkonini beradi. Bu shuni anglatadiki, siz funksiyani istalgan miqdordagi argumentlar, jumladan, nol bilan chaqirishingiz mumkin. Bu kalit so’zi kompilyatorga, kelayotgan argumentlarni individual obekt sifatida emas, balki bir-butun collection sifatida ko’rib chiqilishini anglatadi.
C# ning 11-chi versiyasigacha, agar metodga biz array(yoki harqanday collection) o’tqazmoqchi bo’lsak faqatgina Print(nums); yoki Print(new int[] {1,2,3}); deb yozishimiz kerak edi, yani collection ni avval initsializatsiya qilishimiz kerak edi.

Misol:

var nums = new int[] { 1, 2, 3 }; <-- etibor qiling Print(nums); <-- etibor qiling void Print(int[] array)
{ foreach(var item in array) Console.Write($"{item} ");
}
// output -> 1 2 3
Enter fullscreen mode
Exit fullscreen mode

params bilan esa bunday qilishga hojat yoq

Misol:

Print(1, 2, 3); <-- etibor qiling void Print(params int[] array)
{ foreach(var item in array) Console.Write($"{item} ");
}
// output -> 1 2 3
Enter fullscreen mode
Exit fullscreen mode

Va bu kalit so’zi nafaqat arraylar bilan, balki harqanday IEnumerable vorislariga qollasa boladi.

Misol:

Print(1, 2, 3); <-- etibor qiling void Print(params List<int> list) <-- etibor qiling
{ foreach(var item in list) Console.Write($"{item} ");
}
// output -> 1 2 3
Enter fullscreen mode
Exit fullscreen mode

Params ni ishlatib boshqa tiplar bilan, turli kombinatsiyalar qilish mukin, faqat params metodni eng oxirgi argumenti bo’lishi shart.

Misol:

PrintMessageAndNumbers("uchta son yubordim: ", 1,2,3);
void PrintMessageAndNumbers(string message, params int[] numbers)
{ Console.WriteLine(message); foreach (int number in numbers) { Console.Write($"{number} "); }
}
// output -> uchta son yubordim: 1 2 3
Enter fullscreen mode
Exit fullscreen mode

Shu va shunga o’xshagan ko’plab kombinatsiyalr qilish mumkin.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
If there are enough subscribers to the list, we will do our best to expedite the selected dc location plans. Install docker compose ubuntu. Please set api key.