Indexers in C#

 

Here is an example of how the Indexers work for C#. The code is extremely basic and very easy to follow.

using System;

class IndexExample
{
string Message;

public static void Main()
{
IndexExample obj=new IndexExample("Welcome");

/* This will access the String variable Message
using array like notation
*/
for(int i=0;i < obj.Length;i++)
{
Console.WriteLine(obj[i]);
}
obj[obj.Length-1]="e to C#";

Console.WriteLine(obj.Message);

}

public IndexExample(string s)
{
Message=s;
}

public string this[int i]
{
get
{
if(i >= 0 && i < Message.Length)
{
return Message.Substring(i,1);
}
else
{
return "";
}
}
set
{
if(i >= 0 && i < Message.Length)
{
Message=Message.Substring(0,i) + value + Message.Substring(i+1);
}
}
}

public int Length
{
get
{
if(Message!=null)
{
return Message.Length;
}
else
return 0;
}
}
}

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!