Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class with method taking a different generic class

Tags:

c#

generics

Sorry for asking what seems like such an obvious question.

I have an "adapter" generic class of type T where T is a defined interface. I want to create a method in that class which takes a different type of generic adapter.

public interface ICommon { }
public class TypeOne : ICommon { }
public class TypeTwo : ICommon { }

public class Adapter<T> where T : ICommon
{
    void TakeAnotherType(Adapter<S> other)
    { }
}

This gives me a compilation error Cannot resolve symbol 'S'.

I would like to be able to do;

    MyOne one = new Adapter<TypeOne>();
    MyTwo two = new Adapter<TypeTwo>();
    one.TakeAnotherType(two);

If I change the method to take Adapter<T> then it complains that "two" isn't of type Adapter<TypeOne>

like image 776
Dead account Avatar asked Mar 20 '26 19:03

Dead account


2 Answers

void TakeAnotherType<S>(Adapter<S> other) where S:ICommon
{ }

Because the generic type T of Adapter is constrained to ICommon, it is important to also constrain S in the same way, as this is used as the generic type for Adapter<T>, so it must also satisfy the ICommon constraint.

like image 73
spender Avatar answered Mar 23 '26 09:03

spender


Just change

void TakeAnotherType(Adapter<S> other)

into

void TakeAnotherType<S>(Adapter<S> other) where S : ICommon

and it should work.

like image 39
Daniel Brückner Avatar answered Mar 23 '26 10:03

Daniel Brückner