Thursday, January 8, 2009

Indexer example in C#

using System;
namespace Indexer
{
class Program
{
static void Main(string[] args)
{
TestObject obj1 = new TestObject();
TestObject obj2 = new TestObject();

obj1.AddData(new[] { "this", "is", "test", "one", "!?" });
obj2.AddData(new[] { "this", "is", "another", "test", "!" });

// output to check object
OutputObject(obj1, "OBJ1");
OutputObject(obj2, "OBJ2");

obj1[1] = "was";
obj2[1] = "used to be";

// output to check object
OutputObject(obj1, "OBJ1");
OutputObject(obj2, "OBJ2");
}

public static void OutputObject(TestObject obj, string name)
{
for (int i = 0; i < 5; i++)
Console.WriteLine(string.Format("{0}: {1}", name, obj[i]));
}
}

class TestObject
{
private readonly string[] store = new string[5];

public string this[int index]
{
get { return store[index]; }
set { store[index] = value; }
}

public void AddData(string[] objData)
{
for (int i = 0; i < 5; i++)
store[i] = objData[i];
}
}
}

No comments: