user4664405
user4664405

Reputation:

Calling a generic method with some known type arguments

I'm trying to call a generic but don't know how this should work. I looked around the internet and could not find a solution whichmatches my case.

I got following method:

public void method<T>(string name, string sheet, List<List<T>> xList, List<List<T>> yList)

Now I want to simply invoke this method. When I do so I get an error and it tells me that I have to specify the type arguments. When I specify them then it tells me that a "one-type-argument" is needed. What am I doing wrong here? I read that this should be done by reflection or something else but can't get it to work.

I tried to invoke the method with:

method<string, string, List<List<DateTime>>, List<List<Double>>>(name, sheet, xList, yList)

but this does not work!

Upvotes: 2

Views: 503

Answers (3)

Strahinja Vladetic
Strahinja Vladetic

Reputation: 331

The generic type on your xlist and ylist must be the same. For example this works.

void Main() {
    var foo = new List<List<Foo>>();
    var foo2 = new List<List<Foo>>();
    method("sdf", "sdf", foo, foo2);
}

class Foo{}

But in order to pass two lists of different types you would have to change your method signature to public void method<T,U>(string name, string sheet, List<List<T>> xList, List<List<U>> yList). Then something like this...

void Main() {
    var foo = new List<List<Foo>>();
    var bar = new List<List<Bar>>();
    method("sdf", "sdf", foo, bar);
}

class Foo{}
class Bar{}

Would be possible.

Upvotes: 0

Boris Sokolov
Boris Sokolov

Reputation: 1803

You need

public void method<T1, T2>(string name, string sheet, List<List<T1>> xList, List<List<T2>> yList)

instead of

public void method<T>(string name, string sheet, List<List<T>> xList, List<List<T>> yList)

Upvotes: 6

mrsargent
mrsargent

Reputation: 2442

you only have 1 generic parameter. If T is a string then you would invoke your method like

method<string>(name,sheet,xList,yList);

if T is a DateTime then you would invoke like

method<DateTime>(name,sheet,xList,yList);

Or if you need 2 generic Parameters then you would do

method<T,U>(string name,string sheet,List<List<T>> xList, List<List<U>> xList);

And invoke like

  method<DateTime,Double>(name,sheet,xList,yList);

Upvotes: 0

Related Questions