-1

I ran across something I don't understand today. Consider the following snippet:

public class EventStreamCollection<TKey, TValue>
{
    private readonly ConcurrentDictionary<TKey, TValue> _dictionary = new ConcurrentDictionary<TKey, TValue>();
    private readonly Func<TKey, TValue> _factory;
    public EventStreamCollection(Func<TKey, TValue> factory)
    {
        _factory = factory;
    }

    public TValue this[TKey key] => _dictionary.GetOrAdd(key, _factory);
}

What is this line

public TValue this[TKey key] => _dictionary.GetOrAdd(key, _factory);

It has no name that I can see. If it did, I guess it would be a property? What is it and how does it work?

Christopher Pisz
  • 3,757
  • 4
  • 29
  • 65

1 Answers1

8

That is a read-only, indexer property.

Indexers use this as the name. It allows you to support square brackets on an instance of your your type.

Using the => syntax, it makes it read-only.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445