khoshghadam
khoshghadam

Reputation: 89

Lambda Expression error when trying to call it

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

Answers (1)

alex
alex

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

Related Questions