C# - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Indexers

C# Indexers

shape Description

C# Indexers are called as smart arrays which allow an instance of class or struct to be indexed like an array or virtual array. Representation of indexers is same as properties and modifier can be private, public, protected or internal.

shape Syntax

this[argument list] { get { //Return the value } set { //set the values } }

shape Example

[csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPLessons { class Program { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = "Hello World"; stringCollection[1] = "Welcome"; stringCollection[2] = "Good Noon!"; for (int i = 0; i < 3; i++) { System.Console.WriteLine(stringCollection[i]); } } class SampleCollection<T> { private string[] arr = new string[100]; // Define the indexer, which will allow client code public string this[int i] { get { // This indexer is very simple, and just returns or sets // the corresponding element from the internal array. return arr[i]; } set { arr[i] = value; } } } } } [/csharp] Output:

Overloaded Indexers

shape Description

Overloaded Indexers can be used with multiple parameter and overloading is also possible on indexers.

shape Example

[csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OverLoadingIndexer { class Friends { private string[] Member; // Private data member, its an array public Friends(int n) { Member = new string[n]; for (int i = 0; i < n; i++) Member[i] = "empty"; } public string this[int i] //Its an indexer and looks like property definition { set { Member[i] = value; } get { return Member[i]; } } public string this[string item] //Indexer Overlading with string in the place of index position and its a write only { set { for (int i = 0; i < Member.Length; i++) { if (Member[i] == item) { Member[i] = value; break; } } } } public void Show() // display the contents of array { for (int i = 0; i < Member.Length; i++) Console.WriteLine(Member[i]); Console.WriteLine(); } } class Program { static void Main(string[] args) { Friends FriendsofJames = new Friends(2); //Following statements are used to assign different names to "FriendsofJohn" Object FriendsofJames[0] = "John"; // Object behaves like an array FriendsofJames[1] = "Mark"; Console.WriteLine("Friends list of John :"); FriendsofJames.Show(); //We could change/modify the content using friendname instead of index position FriendsofJames["Bharat"] = "Bharat"; // invokes indexer with string parameter FriendsofJames["Kumar"] = "Kumar"; Console.WriteLine("Friends list after update"); FriendsofJames.Show(); } } } [/csharp] Output: