Saturday, 22 March 2014

what is indexer in c# ?

An indexer enables you to use an index as an object to obtain values stored within the object, In essence this enables you to treat an object like array.

An indexer is also simile to a property. As with properties, you can get and set when defining an indexer.
When you define a property, you define a property name with indexer, instead of creating name as you do with properties, you use this keyword, which refers to the object instance and thus the object name is used.

@Code snippet
Defining my class where we defined the index of array as string type
public class MyClass
    {
        private string[] data = new string[5];
        public string this[int index]
        {
            get { return data[index]; } ;
            set { data[index] = value; };
               
        }
    }
Use of class and assign the value
class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            mc[0] = "Test";
            mc[1] = "12";
            mc[2] = "value";
        }
    }

No comments:

Post a Comment

Others

You will like to read it