A.D.
A.D.

Reputation: 1116

how to properly use a C# indexer property

I am taking over a WPF C# team project.

One of the class inherits from an abstract class having this property:

[Dynamic]
        public dynamic this[string key] { get; set; }

I m not familiar with this but I take it it sets an indexer property the class objects?

I need to mock such an object by adding a variable to this indexer. How am I supposed to do? I was expecting something like this:

this.Add(myKey, myValue);

but the compiler strongly objects :)

How am I supposed to add items into this indexer??

thx

Upvotes: 0

Views: 101

Answers (1)

Peter Morris
Peter Morris

Reputation: 23224

An indexer on a class makes instances look as though they are some kind of array keyed by whatever parameters you wish rather than only integers

var existingValue = this["someKey"];
this["someKey"] = newValue;

To implement the class you'd do something like this

public class Mine : ThatAbstractClass
{
  Dictionary<string, dynamic> IndexerValues = new Dictionary<string, dynamic>();

  public override dynamic this[string key]
  {
    get { return IndexerValues[key]; }
    set { IndexerValues[key] = value; }
  }
}

Upvotes: 4

Related Questions