How is it possible for ReadOnlyCollection to implement IList? The latter requires implementation of the Add method, and the ReadOnlyCollection does not implement this. However, ReadOnlyCollection is concrete and can be instantiated…
Edit
The following code will not compile on my machine:
static void Main(string[] args)
{
List<string> people = new List<string>(){
"Sidney",
"Jim",
"Bob"};
ReadOnlyCollection<string> readOnlyPeople = new ReadOnlyCollection<string>(people);
readOnlyPeople.Add("Frank");
}
The call to “Add” in the last statement is now underlined in blue in Visual Studio 2010.
It does implement Add, the implementation simply throws a
NotSupportedException.The implementation uses “explicit interface implementation“, which is a way of implementing interfaces without directly exposing interface methods as public on the implementing class. It’s most useful when you have a class that implements more than one interface that defines the same member (see the example at the link). Basically, it looks something like this:
Notice how the add method isn’t public, so if you have an instance of
ReadOnlyCollection<T>, you can’t directly callAddon it. What you can do however, if you want to see the exception, is cast your instance to the interface:The other way you could achieve it is to declare your variable as an
IList<T>directly: