Hungry Beast
Hungry Beast

Reputation: 3735

Generics and Inheritance Problem

I'm tempted to say this problem is with my general architecture but either way it's probably easier to show as an example than it would be to describe.

public class AppUserBase
{
}

public class AppUserAbc : AppUserBase
{
}

public class ManagerBase<T> where T : AppUserBase
{
    protected AppUserCollection<T> _users = new AppUserCollection<T>();
}

public class ManagerAbc : ManagerBase<AppUserAbc>
{

}

public static class Program
{
    public static void Main()
    {
        ManagerAbc x = new ManagerAbc();
        DoSomething(x); //fails
    }

    public static void DoSomething<M,U>(ManagerBase<AppUserBase> manager) where M : ManagerBase<U> where U : AppUserBase
    {
        //do something!
    }
}

I hope what I'm trying to do is easy to see and what I should be doing is even easier to explain to me :-).

Upvotes: 0

Views: 139

Answers (2)

Tomas Jansson
Tomas Jansson

Reputation: 23472

That want work, as you probably know. The reason is that ManagerAbc is not of type ManagerBase<AppUserBase>. It doesn't help that the generic part is of the same type. You could try to change to:

public static void DoSomething<M,U>(ManagerBase<U> manager) where M : Manager<U> where U : AppUserBase

Upvotes: 0

user47589
user47589

Reputation:

It's because you have two type parameters but only one is in the method signature, so it can't infer both. The other is not needed. Change your method signature to:

public static void DoSomething<U>(ManagerBase<U> manager)
    where U : AppUserBase
{
    //do something!
}

Upvotes: 3

Related Questions