I have a generic type Store<T> and use Activator to make an instance of this type. Now how, after using the Activator, can I cast the resulted object of type object back to the instantiated type? I know the type that I used to instantiate the generic. Please see the following code:
class Store<T> where T : IStorable
{}
class Beer : IStorable
{}
class BeerStore : Store<Beer>
{}
Type storeType = someObjectThatImplementsIStorable.GetType();
Type classType = typeof(Store<>);
Type[] typeParams = new Type[] { storeType };
Type constructedType = classType.MakeGenericType(typeParams);
object x = Activator.CreateInstance(constructedType, new object[] { someParameter });
What I would like to do is something like this:
var store = (Store<typeof(objectThatImplementsIStorable)>)x;
but that doesn't work for obvious reasons. As an alternative I tried:
var store = (Store<IStorable>)x;
which could possibly work in my opinion, but gives an InvalidCastException.
How do I get access again to the Store<T> methods that I know are in the object x?
obviousreason more obvious? Or just tell us what is the reason. Or do you really meantypeof..., not substituting it with your type?Store<someObjectThatImplementsIStorable>. So the Activator instantiates the correct object but boxes it in anobject, and now I would like to unbox it again.object, and now I would like to downcast it" (or something like that).