Jonathon Reinhart
Jonathon Reinhart

Reputation: 137527

C# List<T> hides properties?

Possible Duplicate:
How does List<T> make IsReadOnly private when IsReadOnly is an interface member?

Okay, this is driving me nuts. List<T> implements IList<T>. However,

IList<int> list = new List<int>();
bool b = list.IsReadOnly;
bool c = ((List<int>)list).IsReadOnly;    // Error

The error is:

'System.Collections.Generic.List' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)

How can this be? Doesn't this violate the very rule that we tell everyone, about not hiding members? What is the implementation detail here?

Upvotes: 1

Views: 423

Answers (4)

BrokenGlass
BrokenGlass

Reputation: 160992

List<T> implements IList<T> explicitly so you have to cast the object to the interface before being able to access IsReadOnly . From MSDN:

A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface

Upvotes: 1

Jay
Jay

Reputation: 57959

Explicit interface implementation, something like:

bool IList<T>.IsReadOnly { get; }

Upvotes: 0

BFree
BFree

Reputation: 103770

If you look at the List class, you'll see this:

 bool IList.IsReadOnly { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
        get; }

All that's really relevant is that IsReadOnly is declared using the explicit implementation which means that property can only be seen if the object is declared as that of IList.

Upvotes: 0

Digicoder
Digicoder

Reputation: 1875

Because the implementation is via an explicit interface implementation.

Meaning that it's defined as

bool IList<T>.IsReadOnly { get; set; //etc }

http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx

And that is why it's not off of List.

Upvotes: 5

Related Questions