Roey Nissim
Roey Nissim

Reputation: 555

Implementing generics in a function using Func

I have a follow static function:

public static string codeList<T>(List<T> thelist, Func<T, string> coder);

using this function with my own objects is not problem for example:

string code = codeList<MyClass>(myclassList, MyClass.code);

Where MyClass.code is a static function (defined in MyClass) that gets MyClass and returns string.

The problem is when I try to use this function with List<int> or List<double> what I do now is predefining statics like Func<int,string> intCoder = (x) => x.ToString(); and Func<double,string> (x) => x.ToString(); and use them. Is there another way of doing that? something like:

string code = codeList<int>(intList, Int32.ToString);

Upvotes: 0

Views: 112

Answers (2)

Amiram Korach
Amiram Korach

Reputation: 13286

You don't have to declare a variable for the func. You can just put the lambda expression as the parameter value

string code = codeList(intList, i => i.ToString());

Upvotes: 1

Jon
Jon

Reputation: 437376

You can do this with

string code = codeList<int>(intList, Convert.ToString);

It just so happens that Convert.ToString has an overload with the appropriate signature.

The problem with int.ToString is that none of its overloads have the appropriate signature (they don't take an int parameter as it is implied). In that case there would be nothing you could do apart from defining an adapter function.

Upvotes: 2

Related Questions