Thursday, 3 May 2012

C# Indexers

An indexer is a special type of property and it has getters and setters as a standard property do.

You can access to collections contained in a class using the familiar [ ] syntax of arrays.
It's quite handy although it may be confusing if you're not familiar with it.
http://msdn.microsoft.com/en-us/library/vstudio/6x16t2tx.aspx
----------------------------------------------------------------------------------
type this [type argument]
{       
    get
    {
        // do something return type;        
    };
         set // optional
    {
        // do something
    };
}
----------------------------------------------------------------------------------
namespace IndexersExample
{
    class People:LinkedList<Person>
    {     
        public Person this[string nametoSearch]
        {
            get
            {
                Person found=null;
                foreach (Person p in this)
                {
                    if (p.Name.Equals(nametoSearch))
                    {
                        found = p;
                    }
                }
                return found;
            }
        }
    }
}
----------------------------------------------------------------------------------

No comments:

Post a Comment