The Collection<T>
class implements multiple interfaces, one of them being ICollection
. The ICollection
interface has 2 properties that are not implemented in Collection<T>
.
In C# I believe you have to implement all the methods and properties of an Interface in the class that inherits it. So how is Collection<T>
class allowed to get away with it?
This is called explicitly implementing an interface. You can make a member not visible from the outside unless the object reference is converted to the interface type.
In the context of Collection<T>
implementing ICollection
, the interface in question defines legacy methods that existed before generics were introduced to C#. You could say it is the 'old ugly' way of managing collections.
The implementors decided to hide these ugly methods, while still providing its functionality to the caller.
var x = new Collection<int>();
object syncRoot = x.SyncRoot; //CS1061: Collection<int> does not contain a ....
ICollection collection = x;
syncRoot = collection.SyncRoot; //ok
Another scenario is where there is a conflict, usually due to external interfaces that are not well designed, and cannot be changed. An example:
interface IFile
{
void Save();
}
interface IDatabaseRecord
{
void Save();
}
class Customer : IFile, IDatabaseRecord
{
public void Save()
{
//what to do here?
}
}
This may be overcome by implementing the method explicitly:
class Customer : IFile, IDatabaseRecord
{
void IFile.Save() { }
void IDatabaseRecord.Save() { }
}
Note that this is almost always a code smell - it could confuse the caller into thinking a method is not present, or calling the wrong implementation (which caused this question to be posted in the first place).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With