Casting an object to a generic interface

If I understand the question, then the most common approach would be to declare a non-generic base-interface, i.e.

internal interface IRelativeTo
{
    object getRelativeTo(); // or maybe something else non-generic
    void setRelativeTo(object relativeTo);
}
internal interface IRelativeTo<T> : IRelativeTo
    where T : IObject
{
    new T getRelativeTo();
    new void setRelativeTo(T relativeTo);
}

Another option is for you to code largely in generics… i.e. you have methods like

void DoSomething<T>() where T : IObject
{
    IRelativeTo<IObject> foo = // etc
}

If the IRelativeTo<T> is an argument to DoSomething(), then usually you don’t need to specify the generic type argument yourself – the compiler will infer it – i.e.

DoSomething(foo);

rather than

DoSomething<SomeType>(foo);

There are benefits to both approaches.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)