Posted by: savagerider | September 2, 2007

indexer

We can make use of indexer to group a collection of class or type together just like an array. First, we could make use of param keyword in the signature to cater for multiple input values. Then, we use indexer to access array like property item.


  static void Main(string[] args)
  {
  testIndexer test = new testIndexer("test", "test1", "test2", "test3", "test4");
  for (int i=0; i < test.getCollectionSize() ; i++)
  {
  Console.WriteLine("Value is {0}", test[i]);
  }
  Console.ReadKey();
  }
  }
public class testIndexer : testInter
  {
  string []testString = new string[255];
  int ctr = 0;
public testIndexer(params Object[] values)
  {
  foreach (string s in values)
  {
  testString[ctr++] = s;
  }
  }

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

public int getCollectionSize()
  {
  return ctr;
  }
  }

interface testInter
  {
  int getCollectionSize();

}

public string this[int index] make the stored array can be accessed like property item. With the param keyword in the constructor we could cater for multiple inputs. The format is like:

 param Type[] variableName

Collection without implementing IEnumerable and IEnumerator cannot be used in foreach case. We use IEnumerable to implement GetEnumerator which returns the instance of Enumeration.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.