I have the following method where T is used inside a Func:
public void DoSomething<T>(string someString, Func<T, bool> someMethod)
{
if(someCondition)
{
string A;
bool resultA = someMethod(A);
}
else
{
string[] B;
bool resultB = someMethod(B);
}
// Some other stuff here ...
}
I am invoking the DoSomething method in the following manner:
DoSomething<string>("abc", someMethod);
DoSomething<string[]>("abc", someMethod);
And the someMethod exists with the following definitions:
bool someMethod(string simpleString);
bool someMethod(string[] stringArray);
Now the compilation fails with the following errors in method DoSomething:
cannot convert from 'string' to 'T'
cannot convert from 'string[]' to 'T'
I am unable to figure out if there is a solution to the problem, or what I am trying is not feasible. It looks similar to question How can I pass in a func with a generic type parameter?, though it was not helpful for my scenario.
Your example seems a little inconsistent, but if you were writing things generically, it should look more like this:
public void DoSomething<T>(string someString, Func<T, bool> someMethod)
{
T a;
someMethod(a);
}
Notice that instead of using if to choose between types, and then declaring the type as either a string or string[], we simply declare the type as T, which will get substituted when the code is compiled so that it will be appropriate for the function.
The moment you find yourself picking between types using if or switch case, you probably don't want a generic solution; the logic isn't, in fact, generic at all. It is specific. In that sort of case, just write two prototypes:
public void DoSomething(string someString, Func<string, bool> someMethod)
{
string A;
bool resultA = someMethod(A);
}
public void DoSomething(string someString, Func<string[], bool> someMethod)
{
string[] A;
bool resultA = someMethod(A);
}
This is known as method overloading. The compiler will automatically pick the right method with the right arguments by inferring the types from the supplied function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With