ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Indexer
    C# 2019. 6. 6. 11:00

    What is Indexer?

     

    Indexer is a structure that makes it possible to deal with class as array by accessing array. Indexer is a structure that makes it possible to deal with class as array by accessing array in object. Indexer is consisted of "get" accessor and "set" accessor just like property.

     

    definition of Indexer

     

    Indexer is defined as,

     

    read only indexer when set accessor is not specified.

     

    write only indexer when get accessor is not specified.

     

    public int this[int i]
            {
                get
                {
                    return a[i]
                }

                set
                {
                    a[i] = value;
                }
            }

     

    How to use Indexer

     

    how to use Indexer is same as that of property. On the example below, kz is dealt as as  array.

     

    class Kazu1
        {
            int[] suji = new int[4];
            public int this[int i];
            get
            {
                return suji[i];
            }
            set
            {
                suji[i] = value;
            }
        }
        class kazu2
            {
                static void Main()
                {
                    Kazu1 kz = new Kazu1();
                    kz[0] = 1;
                    kz[1] = 2;
                    kz[2] = 3;
                    kz[3] = 4;

                    for (int i = 1; i <= 3; i++)
                    {
                        Console.WriteLine(kz[i]);
                    }
                }
            }

    'C#' 카테고리의 다른 글

    메모리의 특징 이해하기  (0) 2019.06.10
    C# polymorphism (2/4) - Override  (0) 2019.06.06
    C# polymorphism (1/4) - Overloading  (0) 2019.06.05
    Params  (0) 2019.06.04
    Stack , Heap  (0) 2019.06.01
Designed by Tistory.