User Tools

Site Tools


notes:csharp:indexers

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
notes:csharp:indexers [2015/06/24]
admin created
— (current)
Line 1: Line 1:
-====== Indexers in C# ====== 
- 
-Indexers are useful to access elements in a class or struct that encapsulate a list or a dictionary. A class or a struct can define multiple indexers, each with parameters of different types. ​ 
- 
-Implementing an indexer: 
-<code csharp> 
-class Tagline 
-{ 
-    string[] words = "One ring to rule them all"​.Split();​ 
- 
-    // Indexer definition 
-    public string this [int n] 
-    { 
-        get 
-        { 
-            if (n < 0 || n > words.length-1) 
-                throw new IndexOutOfRangeException("​Index out of range."​);​ 
-            else 
-                return words[n]; 
-        } 
-        ​ 
-        set 
-        { 
-            words[n] = value; 
-        } 
-    } 
-} 
-</​code>​ 
- 
- 
-Using the indexer: 
-<code csharp> 
-Tagline s = new Tagline(); 
-Console.WriteLine(s[3]);​ // displays the word "​rule"​ 
-</​code>​ 
- 
- 
-An indexer can take more than one parameter: 
-<code csharp> 
-public string this [int arg1, string arg2] 
-{ 
-    get { ... } 
-    set { ... } 
-} 
-</​code>​ 
  
notes/csharp/indexers.1435177668.txt.gz ยท Last modified: 2015/06/24 by admin