Search code examples
functionc#-3.0delegatesanonymous-methods

Why is one Func valid and the other (almost identical) not


private static Dictionary<Type, Func<string, object>> _parseActions 
                                   = new Dictionary<Type, Func<string, object>>
    {
        { typeof(bool), value => {Convert.ToBoolean(value) ;}}
    };

The above gives an error

Error 14 Not all code paths return a value in lambda expression of type 'System.Func<string,object>'

However this below is ok.

private static Dictionary<Type, Func<string, object>> _parseActions 
                                   = new Dictionary<Type, Func<string, object>>
    {
        { typeof(bool), value => Convert.ToBoolean(value) }
    };

I don't understand the difference between the two. I thought the extra braces in example1 are to allow us to use multiple lines in the anon function so why have they affected the meaning of the code?


Solution

  • The first uses a code block, which will only return a value if you use the return keyword:

    value => { return Convert.ToBoolean(value); }
    

    The second, being just an expression doesn't require an explicit return.