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:
genericType
is known at compile time, cast the return value of MakeGenericType
to an ObservableCollection<T>
using that type of as the generic parameter.dynamic
, not object
.observable
to the type you need, i.e. if you want to register for the CollectionChanged
event, cast it to INotifyCollectionChanged
. If you want to iterate over it, cast it to IEnumerable
.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 ICollection
and use the non-generic Add
method:
ICollection tmp = (ICollection)observable;
tmp.Add(yourObject);