A feature in the C# language that I have noticed that many developers, even some with years of C# experience, have missed is that it is possible to create Indexers.
With Indexers you are able to use square brackets to access specific elements of a class, just like you would in an Array or a List:
Assume that you define an interface for a certain ability that a class can have. That ability being that it should be possible to set and get elements of the class using square brackets. You may define the interface like this:
And a class can implement the interface like this:
Now, a user of the Indexable class will be able to get and set individual elements of the Indexable using the same syntax as for an Array or List:
Of course, in this simple example you would be better off with just a simple List. But for larger, more complex classes using Indexers comes in handy from time to time.
With Indexers you are able to use square brackets to access specific elements of a class, just like you would in an Array or a List:
items = new List<int> { 1, 2, 3, 4 }; var first = items[0];
Assume that you define an interface for a certain ability that a class can have. That ability being that it should be possible to set and get elements of the class using square brackets. You may define the interface like this:
namespace Indexer { public interface IIndexable<T> { T this[int index] { get; set; } } }
And a class can implement the interface like this:
using System.Collections.Generic; namespace Indexer { internal class Indexable : IIndexable<int> { private readonly IList<int> items; public Indexable() { items = new List<int> { 1, 2, 3, 4 }; } public int this[int index] { get => items[index]; set => items[index] = value; } } }
Now, a user of the Indexable class will be able to get and set individual elements of the Indexable using the same syntax as for an Array or List:
using System; namespace Indexer { public class IndexerUser { public void UseIndexable() { var indexable = new Indexable(); Console.WriteLine(indexable[0]); indexable[3] = 8; Console.WriteLine(indexable[3]); } } }
Of course, in this simple example you would be better off with just a simple List. But for larger, more complex classes using Indexers comes in handy from time to time.
Kommentarer
Skicka en kommentar