Windows Phone Developers

Saturday, October 18, 2008

Object Arrays in C# using Indexers

C# Array of Objects / Object Arrays in C# using Indexers / Indexers in C# / Operator[] in C#

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

In the following example, a generic class is defined and provided with simple get and set accessor methods as a means of assigning and retrieving values.

class ClsTea

{

private string[] brands = new string[12];

public string this[int index]

{

get { return brands[index]; }

set { brands[index] = value; }

}

private string _locale;

public string Locale

{

get { return _locale; }

set { _locale = value; }

}

}

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access just as an array. Indexers are most frequently implemented in types whose primary purpose is to encapsulate an internal collection or array.

The following code shows the usage of Indexers. Object MyTea can be referenced through an index much like referencing array elements.

static void Main(string[] args)

{

ClsTea MyTea = new ClsTea();

MyTea[0] = "Tata";

MyTea [1] = "Tetley";

MyTea[2] = "Brooke Bond";

Console.WriteLine("No 1 Brand is " + MyTea[0]);

MyTea.Locale = "Ooty";

Console.WriteLine("British Tea is exported from " + MyTea.Locale);

}

  • Indexers enable objects to be indexed in a similar manner to arrays.
  • A get accessor returns a value. A set accessor assigns a value.
  • The this keyword is used to define the indexers.
  • The value keyword is used to define the value being assigned by the set indexer.
  • Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
  • Indexers can be overloaded.
  • Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.

How to create Object Array in .Net (C#), C# Array of User Defined Type , Indexers in C#, C# Indexer example, .Net Indexer examples


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005