| Forums.Sureshkumar.net : A Perfect Place to Share Knowledge Blogs Games Magazines |
|
|||||||
| vb / asp.net Interview / Technical Questions Kindly solve an many as questions you can. It will sharpen your skills and those solutions will help others too. |
![]() |
|
|
LinkBack | Thread Tools | Rate Thread | Display Modes |
|
|
#2 (permalink) |
|
Junior Member
Join Date: Aug 2008
Posts: 1
Thanks: 0 Thanked 0 Times in 0 Posts Thanks: 0
Thanked 0 Times in 0 Posts
Rep Power: 1
|
Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessors take parameters.
// cs_keyword_indexers.cs using System; class IndexerClass { private int [] myArray = new int[100]; public int this [int index] // Indexer declaration { get { // Check the index limits. if (index < 0 || index >= 100) return 0; else return myArray[index]; } set { if (!(index < 0 || index >= 100)) myArray[index] = value; } } } public class MainClass { public static void Main() { IndexerClass b = new IndexerClass(); // Call the indexer to initialize the elements #3 and #5. b[3] = 256; b[5] = 1024; for (int i=0; i<=10; i++) { Console.WriteLine("Element #{0} = {1}", i, b[i]); } } } Output Element #0 = 0 Element #1 = 0 Element #2 = 0 Element #3 = 256 Element #4 = 0 Element #5 = 1024 Element #6 = 0 Element #7 = 0 Element #8 = 0 Element #9 = 0 Element #10 = 0 Notice that when an indexer's access is evaluated (for example, in a Console.Write statement) the get accessor is invoked. Therefore, if no get accessor exists, a compile-time error occurs. For More see : Indexer Declaration (C#) Indexers Tutorial (C#) |
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | Rate This Thread |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| C# - What is an indexer in C# | preethisingh | vb / asp.net Interview / Technical Questions | 1 | 29-01-08 06:10 PM |