One of the advantages of lambda expressions is that you should evaluate a function only when you need its result.
In the following (simple) example, a text function is evaluated only if there is a record:
public static void PrintLine(Func<string> text, TextWriter writer) { if (writer != null) { writer.WriteLine(text()); } }
Unfortunately, this makes using the code a little ugly. You cannot call it with a constant or variable, for example
PrintLine("Some text", Console.Out);
and should call it like this:
PrintLine(() => "Some text", Console.Out);
The compiler cannot "output" the function without parameters from the passed constant. Are you planning to improve this in future versions of C # or am I missing something?
UPDATE:
I just found a dirty hack:
public class F<T> { private readonly T value; private readonly Func<T> func; public F(T value) { this.value = value; } public F(Func<T> func) {this.func = func; } public static implicit operator F<T>(T value) { return new F<T>(value); } public static implicit operator F<T>(Func<T> func) { return new F<T>(func); } public T Eval() { return this.func != null ? this.func() : this.value; } }
Now I can simply define the function as:
public static void PrintLine(F<string> text, TextWriter writer) { if (writer != null) { writer.WriteLine(text.Eval()); } }
and name it both function and value.
Raauhotz
source share