I just came across one thing in the .NET framework (v4.0) that I cannot understand:
There is the class SortDescriptionCollection
namespace System.ComponentModel
{
public class SortDescriptionCollection : Collection<SortDescription>, INotifyCollectionChanged
{
....
protected event NotifyCollectionChangedEventHandler CollectionChanged;
....
}
}
implementing the Interface INotifyCollectionChanged:
public interface INotifyCollectionChanged
{
event NotifyCollectionChangedEventHandler CollectionChanged;
}
I wanted to use the event on the class but I cannot because it's protected.
That's not the big problem because I can cast the implementation to the Interface and then use it.
But how can that be built? If I try to do with
class MyDerivedType : INotifyCollectionChanged
{
protected event NotifyCollectionChangedEventHandler CollectionChanged;
}
so the compiler says:
'MyDerivedType' does not implement interface member 'System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged'. 'MyDerivedType' cannot implement an interface member because it is not public.
EDIT: I don't think it's a duplicate. I was not asking how to compile the code above, it was the question how the .NET framework seemed to could do that (and obviously it couldn't)
It's an explicitly implemented interface event:
event NotifyCollectionChangedEventHandler INotifyCollectionChanged.CollectionChanged
{
add { CollectionChanged += value; }
remove { CollectionChanged -= value; }
}
So it satisfies the requirements of INotifyCollectionChanged, but it isn't publicly visible on the class itself - perfectly valid.
This usually signalizes intent - this is not supposed to be a part of the public interface of the class. However, if you absolutely do want to access this from the outside, you can just do a cast to the interface:
((INotifyCollectionChanged)myCollection).CollectionChanged
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