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
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
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.
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.