Real-world use cases for C # indexers?

I have seen many examples for C # indices, but how can this help me in real situations.

I know that C # gurus would not add this if it weren’t a serious feature, but I can’t think about the situation in the real world (and not about the fusers) for using indexers.

Note. I understand the question, but it doesn’t help me much.

+41
c #
Feb 02 '10 at 15:15
source share
14 answers

The way I look at indexers is that (right or wrong!), Accessing something by index should be more efficient than accessing it in any other way, because in some way a form or form, class, whose index I use stores some form of index, which allows it to quickly look up values ​​when accessing this path.

A classic example is an array, when you access the element n of an array using the myarray [3] code, the compiler / interpreter knows how large (in memory) the elements of the array are and can consider it as an offset from the beginning of the array. You could also "for(int i = 0; i < myarray.length; i++) { if (i = 3) then { .. do stuff } }" (not that you would ever want!) That would be less effective. It also shows how an array is a bad example.

Let's say you had a collection class that stores, mmm, DVDs, so:

 public class DVDCollection { private Dictionary<string, DVD> store = null; private Dictionary<ProductId, string> dvdsByProductId = null; public DVDCollection() { // gets DVD data from somewhere and stores it *by* TITLE in "store" // stores a lookup set of DVD ProductId and names in "dvdsByProductid" store = new Dictionary<string, DVD>(); dvdsByProductId = new Dictionary<ProductId, string>(); } // Get the DVD concerned, using an index, by product Id public DVD this[ProductId index] { var title = dvdsByProductId[index]; return store[title]; } } 

It’s just my 2p, but, as I said, I always considered the “indexer” a reasonable way to get data from something.

+32
02 Feb 2018-10-02T00
source share

The most obvious examples mentioned by Skurmel are List<T> and Dictionary<TKey, TValue> . Which would you prefer:

 List<string> list = new List<string> { "a", "b", "c" }; string value = list[1]; // This is using an indexer Dictionary<string, string> dictionary = new Dictionary<string, string> { { "foo", "bar" }, { "x", "y" } }; string value = dictionary["x"]; // This is using an indexer 

? Now this can be relatively rare because you need to write an indexer (usually when you create a class similar to a collection), but I suspect that you use them often enough.

+24
Feb 02 2018-10-02T00
source share

Microsoft has an example using an indexer to process a file as an array of bytes.

 public byte this[long index] { // Read one byte at offset index and return it. get { byte[] buffer = new byte[1]; stream.Seek(index, SeekOrigin.Begin); stream.Read(buffer, 0, 1); return buffer[0]; } // Write one byte at offset index and return it. set { byte[] buffer = new byte[1] {value}; stream.Seek(index, SeekOrigin.Begin); stream.Write(buffer, 0, 1); } } 
+8
Feb 02 2018-10-02T00
source share

Let's say you have a collection of objects that you want to be able to index with something other than the order in which it was placed in the collection. In the example below, you can see how you can use the "Location" property for any object and, using the indexer, return all the objects in the collection that match your location, or in the second example, all objects containing a certain graph () of objects .

 class MyCollection { public IEnumerable<MyObject> this[string indexer] { get{ return this.Where(p => p.Location == indexer); } } public IEnumerable<MyObject> this[int size] { get{ return this.Where(p => p.Count() == size);} } } 
+5
Feb 02 2018-10-02T00
source share

Once .NET got generics, the biggest reason for me to implement an indexer (to implement a strongly typed collection) was gone.

+5
Feb 02 2018-10-02T00
source share

This is syntactic sugar for collection type classes . I never had a reason to write such a class. Therefore, I think this is a very rare use in "real life" because the classes using it are already implemented.

+3
Feb 02 2018-10-02T00
source share

ASP.Net exists several times when an index is used, for example, reading something from any request object, session, or application. I often saw that something is stored in the Session or Application object only for use again and again.

+3
02 Feb '10 at 15:33
source share
 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IndexerSample { class FailSoftArray { int[] a; // reference to underlying array public int Length; // Length is public public bool ErrFlag; // indicates outcome of last operation // Construct array given its size. public FailSoftArray(int size) { a = new int[size]; Length = size; } // This is the indexer for FailSoftArray. public int this[int index] { // This is the get accessor. get { if (ok(index)) { ErrFlag = false; return a[index]; } else { ErrFlag = true; return 0; } } // This is the set accessor. set { if (ok(index)) { a[index] = value; ErrFlag = false; } else ErrFlag = true; } } // Return true if index is within bounds. private bool ok(int index) { if (index >= 0 & index < Length) return true; return false; } } class Program { static void Main(string[] args) { FailSoftArray fs = new FailSoftArray(5); int x; // Show quiet failures. Console.WriteLine("Fail quietly."); for (int i = 0; i < (fs.Length * 2); i++) fs[i] = i * 10; for (int i = 0; i < (fs.Length * 2); i++) { x = fs[i]; if (x != -1) Console.Write(x + " "); } Console.WriteLine(); // Now, display failures. Console.WriteLine("\nFail with error reports."); for (int i = 0; i < (fs.Length * 2); i++) { fs[i] = i * 10; if (fs.ErrFlag) Console.WriteLine("fs[" + i + "] out-of-bounds"); } for (int i = 0; i < (fs.Length * 2); i++) { x = fs[i]; if (!fs.ErrFlag) Console.Write(x + " "); else Console.WriteLine("fs[" + i + "] out-of-bounds"); } Console.ReadLine(); } } } 
+2
May 03 '11 at 11:51
source share

http://code-kings.blogspot.in/2012/09/indexers-in-c-5.html

Indexers are elements in a C # program that allow a class to behave like an array. You could use the whole class as an array. In this array you can store any types of variables. Variables are stored in a separate place, but are addressed by the class name itself. Creating indexers for integers, strings, booleans, etc. It would be a feasible idea. These indexers would effectively act on class objects.

Suppose you have created a class indexer that stores the student’s roll number in a class. Also, suppose you created an object of this class named obj1. When you say obj1 [0], you mean the first student in the cast. Similarly, obj1 [1] refers to the 2nd student in the cast.

Therefore, the object takes indexed values ​​to refer to the Integer variable, which is privately or publicly stored in the class. Suppose you did not have this object, then you are probably referencing this way (which will be longer):

 obj1.RollNumberVariable[0] obj1.RollNumberVariable[1]. 

where RollNumberVariable will be an Integer variable that refers to the roll number of the current student object.

More details http://code-kings.blogspot.in/2012/09/indexers-in-c-5.html

+2
Oct 11 '12 at 8:10
source share

Here is the video I created http://www.youtube.com/watch?v=HdtEQqu0yOY , and below is a detailed explanation of the same.

Indexers help access the contained collection in a class using a simplified interface. Its syntactic sugar.

For example, let's say you have a class of clients with a collection of addresses inside it. Now let me say that we would like to get a selection from the Pincode and PhoneNumber collections. Thus, the logical step is that you go and create two overloaded functions that are selected using "PhoneNumber", and the other - "PinCode". You can see in the code below, we have two functions.

 Customer Customers = new Customer(); Customers.getAddress(1001); Customers.getAddress("9090"); 

If you use an indexer, you can simplify the code above as shown in the code below.

 Customer Customers = new Customer(); Address o = Customers[10001]; o = Customers["4320948"]; 

Greetings.

+1
Apr 18 '13 at 1:47
source share

http://code-kings.blogspot.in/2012/09/indexers-in-c-5.html

using System;

namespace Indexers_Example

{

 class Indexers { private Int16[] RollNumberVariable; public Indexers(Int16 size) { RollNumberVariable = new Int16[size]; for (int i = 0; i < size; i++) { RollNumberVariable[i] = 0; } } public Int16 this[int pos] { get { return RollNumberVariable[pos]; } set { RollNumberVariable[pos] = value; } } } 

}

0
Oct 11 '12 at 8:16
source share

Addition to the post @ code-kings.

In addition, a call to RollNumberVariable[0] causes the default collection indexer behavior. Although indexes are actually properties , on your behalf you need to write your own logic when retrieving data. You can easily delegate most of the value of an index parameter to an internal collection, but you can also return any arbitrary value for specific index values.

Just an example - you can have 2+ internal collections in a different format, but the external user will interact with them through one index (which will work as a dispatcher) while this collection will be hidden. This greatly encourages the principle of encapsulation.

0
Oct 11 '12 at 8:30
source share

I am trying to get images from a sequence file. I need some kind of 2D array or cog array to store pixel values. I use indexes instead of arrays, because a cycle through indexes is faster than a cycle through 2D or cogged arrays.

0
Aug 04 '14 at 22:21
source share

You can use the indexer to elegantly provide multi-threaded read / write synchronization in a non-stream safe dictionary (or any insecure collection):

 internal class ThreadSafeIndexerClass { public object this[int key] { get { // Aquire returns IDisposable and does Enter() Exit() on a certain ReaderWriterLockSlim instance using (_readLock.Aquire()) { object subset; _dictionary.TryGetValue(key, out foundValue); return foundValue; } } set { // Aquire returns IDisposable and does Enter() Exit() on a certain ReaderWriterLockSlim instance using (_writeLock.Aquire()) _dictionary[key] = value; } } } 

Useful especially when you do not want to use the heavy ConcurrentDictionary (or any other parallel collection).

0
Nov 01 '16 at 17:15
source share



All Articles