4

I see the following syntax:

var comparer = Comparer<TItem>.Default;

How does this syntax work?

I would have thought that the Comparer would have to be new'd up

shiva
  • 714
  • 10
  • 25

2 Answers2

5

Default is a static property, and because of that can be access without having an instance of Comparer<T>.

A static member cannot be referenced through an instance. Instead, it is referenced through the type name.

Comparer<TItem> is a type name here.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • So it is a generic accessor property which calls a method under the hood and not a static data field. And this means the property can use the specified type dynamically to lookup the default comparer? – shiva Apr 23 '16 at 20:19
  • It is a property, not a field, so yes, it can execute code. – MarcinJuraszek Apr 23 '16 at 20:20
1

The trick to not having to new up a Comparer explicitly is that Default is a property, and properties are allowed to have code. This applies to static properties as well:

static Comparer<T> Default {
    get {
        ...
        return new ClassExtendingComparer<T>();
    }
}

This amounts to a parameter-less factory method accessed using a field/property syntax.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523