Create an indexer property

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This C# code snippet creates an indexer property which can be used to access the class as if it were an array. The Dictionary is not required, but is used only as example. Any class which can be viewed logically as an array could have an indexer.

using System.Collections.Generic;
...
class Client
{
   private Dictionary<int, string> invoices 
      = new Dictionary<int, string>();
 
   public void Add (int id, string value)
      { invoices.Add (id, value); }
 
   public string this [int id]      // indexer
   {            
      get { return invoices[id]; }
      set { invoices[id] = value; }
   }
}
 
public class Test
{
   public static void Main( )
   {
      Client client = new Client();
      client.Add (1, "I005238A");
      Console.WriteLine ("Invoice: " + client[1]); // indexer access
    }	
}

Today's Deals: Electronics

Personal tools