jhonny625 jhonny625 - 1 month ago 6
C# Question

How can I debug this error: "Cannot Convert Lambda Expression to String"?

I am trying to debug the following code, but it is not working.

I upload this pic
http://i68.tinypic.com/2rqoaqc.jpg

This is my code:

using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
static void Main()
{
string input = "code1,code2,#c55+35+97#g,coden,code3,code4,#c44+25+07#gcoden";

string output = Regex.Replace(
input,
"#c(.*?)#g",
m => "#c" + m.Groups[1].Value.Split('+').Sum(int.Parse) + "#");

Console.WriteLine(output);
}
}


And these are the errors I am getting:

ERROR 1:


'int int.Parse(string)' has the wrong return type (CS0407) -


ERROR 2:


The call is ambiguous between the following methods or properties: 'System.Linq.Enumerable.Sum(System.Collections.Generic.IEnumerable, System.Func)' and 'System.Linq.Enumerable.Sum(System.Collections.Generic.IEnumerable, System.Func)' (CS0121)


ERROR 3: - Cannot convert m "lambda" to string


Cannot convert lambda expression to type 'string' because it is not a delegate type (CS1660)

dbc dbc
Answer

You need to use an explicit lambda rather than int.Parse():

    string output = Regex.Replace(
        input,
        "#c(.*?)#g",
        m => "#c" + m.Groups[1].Value.Split('+').Sum(v => int.Parse(v)) + "#");

Notice I replaced int.Parse with v => int.Parse(v). Sample fiddle.

Interestingly enough, this compiles and works as desired in c# 6.0:

    string output = Regex.Replace(
        input,
        "#c(.*?)#g",
        m => "#c" + m.Groups[1].Value.Split('+').Sum(int.Parse) + "#");

Sample Roslyn fiddle. I'm not sure where this change is documented, maybe under New Language Features in C# 6: Improved overload resolution:

There are a number of small improvements to overload resolution, which will likely result in more things just working the way you’d expect them to. The improvements all relate to “betterness” – the way the compiler decides which of two overloads is better for a given argument.

One place where you might notice this (or rather stop noticing a problem!) is when choosing between overloads taking nullable value types. Another is when passing method groups (as opposed to lambdas) to overloads expecting delegates. The details aren’t worth expanding on here – just wanted to let you know!