I’m dealing with reflection stuffs, I’ve got a problem with a reflected instance of ObservableCollection. I mean, if create a new instance of it with:
Type virtualObservable = typeof(ObservableCollection<>);
object observable = virtualObservable.MakeGenericType(genericType)
I’ve got an object, but I can’t use it like a ObservableCollection, that is what I need.
Any clue?
There are three possibilities:
genericTypeis known at compile time, cast the return value ofMakeGenericTypeto anObservableCollection<T>using that type of as the generic parameter.dynamic, notobject.observableto the type you need, i.e. if you want to register for theCollectionChangedevent, cast it toINotifyCollectionChanged. If you want to iterate over it, cast it toIEnumerable.I think you can’t use the first option, because if you could, the whole reflection approach would be unnecessary. The second approach leaves you with no IntelliSense support while developing. I think option 3 is the best one.
Sample for option 3:
If you want to add a new item to the collection, you need to cast it to
ICollectionand use the non-genericAddmethod: