Reputation: 89
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();
}
}
}
Upvotes: 0
Views: 50
Reputation: 12654
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.
Upvotes: 1