User Tools

Site Tools


notes:csharp:indexers

Differences

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

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
notes:csharp:indexers [2018/12/03]
leszek
— (current)
Line 1: Line 1:
-====== Indexers in C# ====== 
- 
-Use indexers to access elements in a class (or a struct) that encapsulates a collection. You can define multiple indexers, each with parameters of different types. ​ 
- 
-Indexers can be: 
-  * virtual or abstract 
-  * declared in interfaces 
-  * read-only or read-write 
-  * can have separate access restrictions for setters and getters 
-  * single-dimension indexers with numeric parameters can participate in data binding 
- 
-Example: Implement 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; 
-        } 
-    } 
-} 
-... 
-// Use the indexer. 
-Tagline s = new Tagline(); 
-Console.WriteLine(s[3]);​ // displays the word "​rule"​ 
-</​code>​ 
- 
- 
-An indexer can take more than one parameter (a multidimensional indexer): 
-<code csharp> 
-public string this [int x, int y] 
-{ 
-    get { ... } 
-    set { ... } 
-} 
- 
-public string this [int arg1, string arg2] 
-{ 
-    get { ... } 
-    set { ... } 
-} 
-</​code>​ 
- 
-An indexer can use noninteger parameters to define maps and dictionaries:​ 
-<code csharp> 
-public City this [string code] 
-{ 
-    get { ... } 
-    set { ... } 
-} 
-</​code>​ 
- 
- 
  
notes/csharp/indexers.1543849982.txt.gz ยท Last modified: 2018/12/03 by leszek