1

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.

a.toraby
  • 3,232
  • 5
  • 41
  • 73
  • possible duplicate of [Can you use generics methods in C# if the type is unknown until runtime?](http://stackoverflow.com/questions/646377/can-you-use-generics-methods-in-c-sharp-if-the-type-is-unknown-until-runtime) – TomDoesCode Jul 13 '15 at 15:39
  • 3
    Every method or type that works with a generic type with generic arguments unknown at compile-time must also be generic - in this way, "generic-ness" is infectious. Just make `CreateConnection` generic (as `CreateConnection`, and you'll be fine. Your last sample works because you indeed passed a *specific* generic type - `Type` is a known class, so `NodeOutput` is a concrete type. It's just like if you used `NodeOutput`, for example. Unlike Java, C# doesn't have anything like `GenericType>`. – Luaan Jul 13 '15 at 15:42
  • @Luan You should make that an answer (along with the answer to the first question), since all of the other answers seem to ignore what you just stated. – Jashaszun Jul 13 '15 at 15:44
  • 1
    Unless those classes have been greatly simplified for this question there is no point in having two identical classes with different names. You should just use the names of the parameters to determine if it's input or output. – juharr Jul 13 '15 at 15:48
  • @juharr I want them to be different classes because I will have a list method that should return all NodeOutput instances within the object using reflection :) – a.toraby Jul 13 '15 at 15:53

2 Answers2

4

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.

rory.ap
  • 34,009
  • 10
  • 83
  • 174
2

Try

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

}
serhiyb
  • 4,753
  • 2
  • 15
  • 24