Q1 Why do new classes from .NET implement interfaces only partially?
Q2 Shall I do the same in my code?
I asked this question here, so I thought, okay that was long time ago, you can have different usage etc etc, and now such implementation is supported only for consistency reasons. But new classes also do that.
Old
int[] list = new int[] {};
IList iList = (IList)list;
ilist.Add(1); //exception here
New
ICollection c = new ConcurrentQueue<int>();
var root = c.SyncRoot; //exception here
UPDATE
I am not worried why I get exceptions, it is clear. But I don't understand why classes implement the well defined contract, but not all the members (which can lead to unpleasant run time exceptions)?
The addition PARTIALLY IMPLEMENTED for statement INTERFACES for implementing interfaces in classes can only be used in test classes. This addition prevents the syntax check error/warning from occurring if not all of the concrete non-optional interface methods are implemented in the test class.
No, you cannot implement an interface partially because in interface all methods are abstract.So,If you have implemented any interface then you must have to override all of its methods. What's the difference between a Java interface and a abstract class.
In C#, you can split the implementation of an interface into multiple files using the partial keyword. The partial keyword indicates that other parts of the interface can be defined anywhere in the namespace. All the parts must use the partial keyword and must be available at compile time to form the final type.
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public , private , and so on.
You could argue that the interfaces weren't granular enough in the original design. For example, most people never use SyncRoot
- it could perhaps have been on a different interface. Likewise, it is unfortunate that no interface offers read-only indexer access, for example.
As it stands, the interfaces are what they are. It is still very convenient to implement the main IList[<T>]
/ICollection[<T>]
/IEnumerable[<T>]
interfaces though - it offers the majority of callers access to what they need... so indexers in the first example, and Add
in the second.
To be fair, they do also offer IsFixedSize
and IsReadOnly
- querying the first would have led you to not call Add
. Re SyncRoot
- that presumably can't make sense inside ConcurrentQueue<T>
, and any implementation would break the logic of the type. Normally I would say "then it isn't that type; don't implement the interface", but to repeat my earlier statement... most people never use SyncRoot
- so I'm OK with it ;p
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