Published: 2014-11-21
This is part 5/17 of my Exploring the .NET CoreFX series.
This is a simple recommendation based on observations from System.Collections.Immutable.
Recommendations
- Keep the implementation of an indexer as trivial as possible to allow the JIT optimization of removing array bounds checking to work. For example, don’t check if a member variable is null; just use it and allow the
NullReferenceExceptionto happen naturally. In other words, use:
public T this[int index]
{
get
{
return this.array[index];
}
}
not:
public T this[int index]
{
get
{
if (this.array == null)
throw new NullReferenceException();
return this.array[index];
}
}