Anonymous function converted to a void returning delegate cannot return a value

Anonymous functions in C# can be converted to delegates. However, if an anonymous function is converted to a delegate with a return type of void, it cannot return a value. This is because void means that the method does not return anything.

Let’s look at an example to understand this better. Consider the following code snippet:


    using System;

    public delegate void MyDelegate();

    public class Program
    {
        static void Main()
        {
            // Anonymous function declaration
            MyDelegate myDelegate = delegate ()
            {
                // This anonymous function has a void return type
                // It cannot return a value
                // Therefore, the following line will give a compilation error
                // return 10;
            };

            myDelegate();

            Console.ReadLine();
        }
    }
  

In the above example, we have declared an anonymous function and converted it to a delegate of type MyDelegate. The MyDelegate delegate has a return type of void.

Inside the anonymous function, we attempt to return a value of 10. However, since the anonymous function has a void return type, this will result in a compilation error. It is not allowed to return a value from a void method.

To fix this error, you can either change the return type of the anonymous function to a non-void type that matches the delegate’s return type or modify the delegate to have a void return type, if returning a value is not necessary.

Same cateogry post

Leave a comment