3

I have a class named Item that I use in my project, and wanted to get/set values inside the class by an indexer function.

I created the indexer function and got the subject error. After some research, it seems like the problem is that the indexer is actually a List.Item, thus my error. I can change the class to Item2 and it compiles, but this class is heavily used and I don't want to rename it if possible. Is this resolvable without changing the name of my class? Or do I just need to forget this and use functions to get/set the values instead of the indexer?

Sample of code that will throw this compile time error:

public class Item
{
    public object this[string var_name]
    {
        get { return null; }
        set { }
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325

1 Answers1

8

Well, it is possible, but you need some extra work for it. You need to add the IndexerName attribute:

public class Item
{
    [System.Runtime.CompilerServices.IndexerName("ItemIndexer")]
    public object this[string var_name]
    {
        get { return null; }
        set { }
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325