When I write a class in C#, I'm often not only using interface types in the public API/signatures, but also as types of the private members:
public class Foo {
private readonly IDictionary<string, Bar> m_Bars; // <-- here
public Foo() {
m_Bars = new Dictionary<string, Bar>();
}
}
There are some occasions when I don't do this, mostly when I need expose some ReadOnly
interface variant of a mutable collection. Most common example would be having a List<T>
I want to expose as IReadOnlyCollection<T>
or IReadOnlyList<T>
; I cannot make the member an ICollection<T>
respectively IList<T>
because those interfaces do not extend their IReadOnly
counterparts to retain binary backwards compatibility and I'd have to add a wrapper to make it work:
public class Foo {
private readonly List<Bar> m_Bars; // <-- not here
public Foo() {
m_Bars = new List<Bar>();
}
public IReadOnlyCollection<Bar> Bars => m_Bars;
}
Protected instance members are kind-of in the middle between private members and the public API, so the general benefits of exposing interfaces rather than classes do apply.
But for private members, does it help/hurt/make any difference? Does it for example introduce additional type checks every time the member is accessed?