Search code examples
c#genericsgeneric-programming

How Can I use generic classes in another method when I dont know what is T?


Suppose we have these classes:

public class NodeOutput<T> : NodeData
{
    public T Value;
    public NodeOutput(string name, T value)
        : base(name)
    {
        this.Value = value;
    }
}
public class NodeInput<T> : NodeData
{
    public T Value;
    public NodeInput(string name, T value)
        : base(name)
    {
        this.Value = value;
    }
 }

How Can I use these classes in another method when I dont know what is T yet? This can not be compiled:

public createConnection(NodeOutput<T> output, NodeInput<T> input)
{

}

But this one seats easy with compiler: Though I'm not sure what does it mean at all!

public Connection(NodeOutput<Type> output, NodeInput<Type> input)
{

}

Here in this function T is not important for me. I just need to save output and input in two variables.


Solution

  • You can declare your other method as generic, too:

    public void CreateConnection<T>(NodeOutput<T> output, NodeInput<T> input)
    {
    
    }
    

    I added a return type void (thanks Dmitry Bychenko for pointing that out). You can change it to whatever you need.

    Also, just a note: this is C#, not Java. The naming convention is upper camel case.