Reputation: 2671
I have a bunch of methods that create same result type ,but their parameter type varies.Assume int
is the result type ,and bool
,int
,float
,etc,etc,
and prototype are like this:
int method1(int param1);
int method2(bool param1);
int method3(float param1);
how can I refactor them to looks like this:
int methodGenericVersion1<T>(T arg1);
By the way ,I cannot see the implementation of those non-generic methods.
EDIT
I want to invoke like this:
methodGenericVersion1<int>(param1);
methodGenericVersion1<bool>(param1);
methodGenericVersion1<float>(param1);
Upvotes: 0
Views: 1432
Reputation: 537
It sounds like you want to dispatch to the 'correct' method based on the actual generic type, like so:
public int GenericMethod<T>(T t)
{
if (t is int)
{
return method1(t as int);
}
else if (t is bool)
{
return method2(t as bool);
}
else if (t is float)
{
return method3(t as float);
}
...
throw new ArgumentInvalidException(...);
}
However, if the goal is to provide a "single method" that can be used polymorphically across a limited range of types, then I question why a generic is necessary. You can use method overloading and get exactly the same developer experience, like so:
public int method(int arg)
{
return method1(arg);
}
public int method(bool arg)
{
return method2(arg);
}
public int method(float arg)
{
return method3(arg);
}
Upvotes: 3
Reputation: 101681
You are so close.Just you need to specify generic parameter within the method name like this:
int methodGenericVersion1<T>(T arg1)
Also you might want to add a struct
constraint if you want to pass value types only:
int methodGenericVersion1<T>(T arg1) where T : struct
Upvotes: 1
Reputation: 115488
You can do something like this:
int Test<T>(T v)
{
return -1;
}
Upvotes: 0