Note that there are some explanatory texts on larger screens.

plurals
  1. POCan a C# lambda expression ever return void?
    primarykey
    data
    text
    <p>I have the following method, and <strong>I want to know if there is anything that can go in place default(void) below</strong> because there is a compiler error that says that void is not valid here:</p> <pre><code>private void applyDefaultsIfNecessary(ApplicationConfiguration configuration) { var defaults = new Dictionary&lt;Predicate&lt;ApplicationConfiguration&gt;, Action&lt;ApplicationConfiguration&gt;&gt;() { // { rule, action } - if rule is true, execute action { (c) =&gt; c.ConnectionString == null , (c) =&gt; c.ConnectionString = "foo" }, { (c) =&gt; c.OutputExcelFilePath == null, (c) =&gt; c.ConnectionString = "bar" }, { (c) =&gt; c.OutputDirectory == null, (c) =&gt; 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) =&gt; item.Key.Invoke(configuration) ? item.Value.Invoke(configuration) : default(void) ); } </code></pre> <p>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:</p> <pre><code>defaults.Select&lt;ApplicationConfiguration, void&gt;((item) =&gt; { if (item.Key.Invoke(configuration)) item.Value.Invoke(configuration); } ); </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload