title: C# lambda expressions and lazy evaluation
body: <p>One advantage of lambda expressions is that you have to evaluate a function only when you need its result.</p>
  
  <p>In the following (simple) example, the text function is only evaluated when a writer is present:</p>
  
  <pre><code>public static void PrintLine(Func&lt;string&gt; text, TextWriter writer)
  {
      if (writer != null)
      {
          writer.WriteLine(text());
      }
  }
  </code></pre>
  
  <p>Unfortunately, this makes using the code a little bit ugly. You cannot call it with a constant or variable like</p>
  
  <pre><code>PrintLine("Some text", Console.Out);
  </code></pre>
  
  <p>and have to call it this way:</p>
  
  <pre><code>PrintLine(() =&gt; "Some text", Console.Out);
  </code></pre>
  
  <p>The compiler is not able to "infer" a parameterless function from the passed constant. Are there any plans to improve this in future versions of C# or am I missing something?</p>
  
  <p>UPDATE:</p>
  
  <p>I just found a dirty hack myself:</p>
  
  <pre><code>    public class F&lt;T&gt;
      {
         private readonly T value;
         private readonly Func&lt;T&gt; func;
  
         public F(T value) { this.value = value; }
         public F(Func&lt;T&gt; func) {this.func = func; }
  
         public static implicit operator F&lt;T&gt;(T value)
         {
              return new F&lt;T&gt;(value);
         }
  
         public static implicit operator F&lt;T&gt;(Func&lt;T&gt; func)
         {
             return new F&lt;T&gt;(func);
         }
  
         public T Eval()
         {
             return this.func != null ? this.func() : this.value;
         }
  }
  </code></pre>
  
  <p>Now i can just define the function as:</p>
  
  <pre><code>public static void PrintLine(F&lt;string&gt; text, TextWriter writer)
  {
      if (writer != null)
      {
          writer.WriteLine(text.Eval());
      }
  }
  </code></pre>
  
  <p>and call it both with a function or a value.</p>