I want use a Lambda Expression but get an error which occurs on the line commented below, when I try to call it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppTestDelegate2
{
public delegate string MyDelegate (int a);
public class ClassRunDelegate
{
public void RunDelegate(MyDelegate a, int b)
{
Console.WriteLine(a(b));
}
}
public class MyHelp
{
public string test(int a)
{
a++;
return a.ToString();
}
}
class Program
{
static void Main(string[] args)
{
MyHelp fhelp = new MyHelp();
//
MyDelegate fdelegate = new MyDelegate(fhelp.test);
ClassRunDelegate cc = new ClassRunDelegate();
cc.RunDelegate(fdelegate, 10);
///
cc.RunDelegate((a, b) => { Console.WriteLine("test"); });// get error this line
Console.ReadLine();
}
}
}
George Duckett
32.6k12 gold badges101 silver badges167 bronze badges
-
What does the error say?George Duckett– George Duckett2013年05月01日 11:16:57 +00:00Commented May 1, 2013 at 11:16
-
That line isn't even valid. I don't know what you are trying to do.Justin– Justin2013年05月01日 11:17:57 +00:00Commented May 1, 2013 at 11:17
1 Answer 1
From your code, MyDelegate should return string, but Console.WriteLine("test") does not return anything, so that does not compile:
cc.RunDelegate((a) => { Console.WriteLine("test"); }, b);
You should either return something after Console.WriteLine or use another type of delegate, with no return value.
answered May 1, 2013 at 11:17
alex
12.7k4 gold badges50 silver badges69 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-cs