-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,402
  • 1
  • 20
  • 54

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
  • 181,601
  • 45
  • 354
  • 430