Quote of the day: A Big Fat Lie - Time Heals All Wounds.

Tuesday, May 26, 2009

Indexers in C#

Indexers

Indexers are also called as smart Arrays in C#. Indexer allows your class to be used like an array. An indexer allows you to use an index on an object to obtain values stored within the object. In other words, it enables you to treat an object like an array and access that object using [ ] array access operator.

Defining an indexer is same as defining properties. Like properties, you use get and set when defining and indexer. Properties are defined using property name but with indexers, instead of creating a name, you use this keyword.

The format for defining an indexer is

this [argument list]
{
get
{
// Get code goes here
}
set
{
// Set code goes here
}
}



Indexer modifier can be private, public, protected or internal. The return type can be any valid C# types. The ‘this’ is a special keyword in C# to indicate the instance of the current class. Indexers in C# must have at least one parameter. Other wise the compiler will generate a compilation error.

Example of Indexer:



using System;
using System.Collections.Specialized;
namespace IndexerExample
{
class PhoneBook
{
ListDictionary nameDictionary = new ListDictionary();
public String this[string name]
{
get
{
return nameDictionary[name].ToString();
}
set
{
nameDictionary.Add(name,value);
}
}
}
class program
{
public static void Main()
{
PhoneBook phoneBook = new PhoneBook();
phoneBook["Joe"] = "111-111-1111";
phoneBook["Jessica"] = "222-222-2222";
phoneBook["John"] = "333-333-3333";
phoneBook["Jade"] = "444-444-4444 ";
phoneBook["Jevon"] = "555-555-5555";

Console.WriteLine("Indexer Example\n\n");
Console.WriteLine("{0}\n{1}\n{2}\n{3}\n{4}\n", phoneBook["Joe"], phoneBook["Jessica"], phoneBook["John"], phoneBook["Jade"], phoneBook["Jevon"]);
Console.WriteLine("\n");
Console.ReadLine();
}
}
}

Thursday, May 14, 2009

Tribute to my old friends

Oh! Those dear Old Friends
I luv to remember them.

How we laughed, How we enjoyed.
The mornings, The evenings and the nights,
We made each other happy.
Never came an occasion to be Sorry.
We were merry and carefree,
Nothing in this world could make us worry.

Oh! Those dear Old Friends
I luv to remember them.

Today they aren't with me
Yet I have their loving memories.
Can I ever forget them
who made my moments merry.
A bond of luv and friendship
unbreakable, strongest relationship.

Oh! Those dear Old Friends
I luv to remember them.

Setting be the sun, long be the shadow
Still Greenery remains in the meadow.
Thats the way I think of them,
Even though I know they cant come
But I wish one day we will meet again,
together we will roam about.

Oh! Those dear Old Friends
I luv to remember them.