tags:

views:

97

answers:

1

Hi

Is there any way to cast to a dynamic generic interface..

Site s = new Site();
IRepository<Site> obj = (IRepository<s.GetType()>)ServiceLocator.Current.GetInstance(t)

obviously the above won't compile with this cast. Is there anyway to do a dynamic cast of a generic interface. I have tried adding a non generic interface but the system is looses objects in the Loc container.

Thanks

Phil

+2  A: 

Dynamic casting is not easily achievable in C#. You can use 'cast-by-example' - but I would not recommend this - it tends to be confusing.

In you case it's unclear why a 'dynamic' cast is even necessary - if you don't know the type at compile time you can't access any of it's methods or properties. What would such a cast gain you? You may as well just write:

IRespository<Site> obj = 
      (IRepository<ISite>)ServiceLocator.Current.GetInstance(t);

If you're inside a generic method, you can always cast to the generic parameter type:

public void SomeMethod<T>( ) 
    where T : new()
{
    T s = new T();
    IRepository<T> obj = (IRepository<T>)ServiceLocator.Current.GetInstance(t)
    // ...
}
LBushkin