DEV Community

Farkhodbek Kamolov
Farkhodbek Kamolov

Posted on

Yashirin indekserga kirish

Bazida 0 indekslangan collectionlarni ohirgi qiymatiga murojat qilishda ko'pchiligimiz yo'l qo'yadigon oddiy bir xatolik bor array[array.Length], va hozirham oramizda bu yerda xatolikni payqamaganlarxam bo'lishi mumkin. Bu error esa o'z vaqtida judaham kichik, payqa qolish qiyin va asabga o'ynaydigon hatoliklardan deb xisoblayman (array[array.Length - 1] to'g'ri varianti).

C# 13-chi versiyasida Implicit Index Access -> yashirincha indeksga murojat degan feature qo'shildi. Bu feature ni ishlatishda bizga caret-^ operatori yordam beradi.

Misol:

int[] nums = new int[5] { 1, 2, 3, 4, 5 };
Conosle.WriteLine(nums[^1]);
// output -> 5
Enter fullscreen mode Exit fullscreen mode

Implicit Index Access feature sini funksionalligi faqatgina ohirgi elementga murojat qilish bilan cheklanib qolmaydi. Bu xususiyat har-qanday 0 indekslangan collection ni oxiridan boshlab har bir qiymatiga murojat qilishda yordam beradi.

Misol:

int[] nums = [1, 2, 3, 4, 5];

for(int i = 1; i <= nums.Length; i++)
    Console.Write($"{nums[^i]} ");
// output -> 5 4 3 2 1
Enter fullscreen mode Exit fullscreen mode

Etibor berish kerak bolga joyi bu funksional ^1(birdan) boshlanadi, bu degani arrayimizni uzunligi n bolsa, oxirgi qiymatning indexi n-1 ga teng, shu bilan birgalikda ^1 = n-1 yaniy eng oxirgi indeksga ko'rsatib turadi, ^2 esa oxirgidan bitta oldingi(^2 = n-2) indeksga teng, va hokazo.
Arrayni teskari o'girish misoliga boshqacharoq qilib ishlatamiz

Misol:

int[] nums = [1, 2, 3, 4, 5];

foreach (var item in ReverseArray(nums))
    Console.Write($"{item} ");

int[] ReverseArray(int[] array)
{
    int[] reversed = new int[array.Length];
    for(int i = 0; i < array.Length; i++) <---
        reversed[i] = array[^(i+1)];      <---

    return reversed;
}

// output -> 5 4 3 2 1
Enter fullscreen mode Exit fullscreen mode

Bu safargi ko'dimizda i 1 ga emas 0 ga teng va array ni oxiridan murojatni boshlash uchun esa array[^(i+1)] ishlatildi.

Bundan tashqari bu feature ni harkim o'z tassavuri yetganicha va albatta C# kompilyatori ruhsat berganicha ishlata oladi. @wahidustoz aytganlaridek "Sky is the limit".

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay