Click here to Skip to main content
15,894,646 members

Response to: Passing a generic class to a non generic method

Revision 2
Mehdi,

Answering this question is quite a trivial thing. You could answer by yourself, you just need to be logical.

You need to start with non-generic method, as this is the most limiting (by the way, why it is not generic? OK, I understand why it could be). What variants do we have?

First, it could expect any fixed parameter type; in this case, it will determine the generic parameter:

C#
public class Node<T> {/*...*/}

public class classname
{ 
    public void SomeMethod(Parameter node) {/*...*/}
}

public class Parameter {/*...*/}

//...

Node<Parameter> parameter = ...
classname instance = ...
instance.SomeMethod(parameter); //isn't it?


Another variant is using wider type. Let starts with the widest, which is System.Object:

C#
public class Node<T> {/*...*/}

public class classname
{ 
    public void SomeMethod(System.Object node) {/*...*/}
}

public class Parameter {/*...*/} //this is any type again, always is System.Object

//...

Node<Parameter> parameter = ...
classname instance = ...
instance.SomeMethod(parameter); //same thing


And finally, the same case as above but with generic constraint; the idea is to use the widest common type instead of System.Object:

C#
public abstract class AbstractParameter {/*...*/}

public class Node<T> where T: AbstractParameter {/*...*/}

public class classname
{ 
    public void SomeMethod(AbstractParameter node) {/*...*/}
}

public class Parameter : AbstractParameter {/*...*/} //this time, any type but derived from AbstractParameter

//...

Node<Parameter> parameter = ...
classname instance = ...
instance.SomeMethod(parameter); //isn't it?


Also, there is a variant with interface instead of abstract class, essentially the same.

That's all, it looks like.

—SA
Posted 7-Dec-11 20:55pm by Sergey Alexandrovich Kryukov.
Tags: