I have a generic class containing a special collection. An instance of this collection is passed to a method as object. Now I have to call one of the generic class’ methods. The problem I see is that I don’t know which type the items in the collection are of so that I can’t cast before using the property.
public class MyGenericCollection<T>: ReadOnlyObservableCollection<T>
{
public bool MyProperty
{
get
{
// do some stuff and return
}
}
}
public bool ProblematicMethod(object argument)
{
MyGenericCollection impossibleCast = (MyGenericCollection) argument;
return impossibleCast.MyProperty;
}
Is there a way around this problem?
In this case, it may be worth adding an interface containing all your non-generic members:
then make the collection implement it:
then take an
IHasMyPropertyin your method:or keep taking
object, but cast to the interface:In other cases you could have a non-generic abstract base class which your generic class extends, but in this case you’re already deriving from a generic class (
ReadOnlyObservableCollection<T>) which removes that option.