views:

78

answers:

2
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?

+11  A: 

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.

Marcelo Cantos
Yep, I posted the question, then looked at it for another ooooh 30 seconds before i realised my mistake :) cheers
runrunraygun
A: 

The first one you are not returning anything and you must explicitly return a value since you have a wrapped it, where the second one you are implicitly returning a value.

To fix it do

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