Search code examples
c#.netreflectionruntimeactivator

Use a reflected instance of ObservableCollection


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?


Solution

  • There are three possibilities:

    1. If genericType is known at compile time, cast the return value of MakeGenericType to an ObservableCollection<T> using that type of as the generic parameter.
    2. If you are on .NET 4.0, make observable of type dynamic, not object.
    3. Cast 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);