Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C# lambda expression ever return void?

I have the following method, and I want to know if there is anything that can go in place default(void) below because there is a compiler error that says that void is not valid here:

private void applyDefaultsIfNecessary(ApplicationConfiguration configuration)
{
    var defaults = new Dictionary<Predicate<ApplicationConfiguration>, Action<ApplicationConfiguration>>()
    {
       // { rule, action } - if rule is true, execute action 
       { (c) => c.ConnectionString == null , (c) => c.ConnectionString = "foo" },
       { (c) => c.OutputExcelFilePath == null, (c) => c.ConnectionString = "bar" },
       { (c) => c.OutputDirectory == null, (c) => c.OutputDirectory = "baz" }

    };

    //Nothing to select, but we want to loop throough the dict and invoke action, if rule is true.
    //It is a pity there is no extension method called DoForEach on collections.
    defaults.Select((item) => item.Key.Invoke(configuration) ? item.Value.Invoke(configuration) : default(void)  );
}

I realize that I can use the if-else statement instead of the ternary operator (or that I could call a dummy method to return void). Also, the Select extension method does not like lambdas that return void. It seems to say that the type cannot be inferred, but of course if I specify the type like this, either:

defaults.Select<ApplicationConfiguration, void>((item) => { if (item.Key.Invoke(configuration)) item.Value.Invoke(configuration); } );

I was curious from a language design standpoint, why we don't have expressions that can return void or the data type for variables that is void.

like image 964
Raghu Dodda Avatar asked Jan 08 '10 17:01

Raghu Dodda


1 Answers

I refer you to section 7.1 of the specification, which states:

[An expression may be classified as] "nothing". This occurs when the expression is an invocation of a method with a return type of void. An expression classified as nothing is only valid in the context of a statement expression.

[Emphasis added].

That is to say that the only time you may use an expression which is a void-returning method invocation is when the expression makes up an entire statement. Like this:

M();
like image 141
Eric Lippert Avatar answered Oct 17 '22 22:10

Eric Lippert