Lijin John Lijin John - 1 month ago 8
C# Question

Not able to understand Indexer in C#

I was going through some code and come across with indexer and i am not able to understand how it is working, here is my code

public class FlyweightFactory
{
Dictionary<string, FlyweightFactory> flyweights = new Dictionary<string, FlyweightFactory>();
public void display() { }
public FlyweightFactory this[string index]
{
get
{
if (!flyweights.ContainsKey(index))
flyweights[index] = new FlyweightFactory();
return flyweights[index];
}
}
}
class Client
{
// Shared state - the images
static FlyweightFactory album = new FlyweightFactory();
static void Main()
{
Client client = new Client();
album["A"].display();
Console.ReadLine();
}

}


in this code i have created an Indexer like this

public FlyweightFactory this[string index]
{
get
{
if (!flyweights.ContainsKey(index))
flyweights[index] = new FlyweightFactory();
return flyweights[index];
}
}


but i when i am trying to make a Indexer like this i am getting an error


album["A"];


but at the same time when i use like this it is working fine


album["A"].display();


please help me understand the working of Indexer, thank you

Answer

You cannot write such statement in C# and it will emit the following error:

error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

Such statement does not fit any of the categories told in the error message.

To fix the error assign this statement to a variable:

var myValue = album["A"];

Now for the indexer:

It allows you to access an item in a collection by the means of a specific key type, in an array you commonly access items by their index such as:

int[] ints = {0, 1, 2, 3};
var int1 = ints[0]; // get first element

But you can implement a different type than int, here I used a string:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Tests
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            // generate some data
            var artist = new Artist {Name = "Britney", Surname = "Spears"};
            var artists = new[] {artist};
            var collection = new ArtistCollection(artists);

            // find an artist by its name, using the custom indexer
            var artist1 = collection["Britney"];
        }
    }

    public class Artist
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }

    public class ArtistCollection : Collection<Artist>
    {
        public ArtistCollection()
        {
        }

        public ArtistCollection(IList<Artist> list) : base(list)
        {
        }

        /// <summary>
        ///     Gets an artist by name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Artist this[string name]
        {
            get
            {
                if (name == null)
                    throw new ArgumentNullException(nameof(name));
                var artist = this.SingleOrDefault(s => s.Name == name);
                return artist;
            }
        }
    }
}