Florian Rappl, MVP Visual C#
using lambda expressions to boost your efficiency
C#, WinForms, WPF
C#, JS, ASP.NET MVC
C/C++, MIC, IB
=>
operatorreturn
statement is only needed within curly brackets
Func<double, double> squ = x => x * x;
Func<double, double, double> f = (x, y) => x * x + y;
Action dot = () => Console.Write(".");
Action<string> print = (str) => Console.WriteLine(str);
Action<string, params object[]> printf = (s, o) =gt; Console.WriteLine(s, o);
var mc = (Func<double>)(
() => {
var ran = new Random();
var d = ran.NextDouble();
return d > 0.5 ? d * d : 1.0 + 1.0 / d;
});
async
can be specified for using await
Expression<T>
as target type generates a view of the related expression tree
public void GiveMeSomeLambda<T>(Func<T, T> theLambda) { /* ... */ }
//Here stating the argument type explicitly makes sense (one way)
GiveMeSomeLambda((double s) => s * s);
Func<double, Task<double>> f = async x =>
{
var res = await Task.Run(/* Long running task with some result depending on x */);
return res;
};
((string s, int no) => {
// Do Something here!
})("Example", 8);
class MyClass
{
//Let's assume the class is dependent on some object
public MyClass(Settings settings)
{
/* Read some settings of the user */
//A property (or method) of the object is required to determine the status
if(settings.EnableAutoSave)
AutoSave = () => { /* Perform Auto Save */ };
else
AutoSave = () => { }; //Just do nothing!
}
public Action AutoSave { get; private set; }
}
SynchronizationContext
for invoking events
SynchronizationContext context = SynchronizationContext.Current ?? new SynchronizationContext();
public event EventHandler<MyEventArgs> SomethingHappend;
public void RaiseSomethingHappend()
{
if(SomethingHappend != null)
context.Post(o => SomethingHappend(this, new MyEventArgs(field1, ..., fieldn)), null);
}
switch
Dictionary
gives us more flexibility:
Dictionary<string, Func<double, double>> functions = new Dictionary<string, Func<double>>();
void Init()
{
functions.Add("sin", Math.Sin); functions.Add("cos", Math.Cos); functions.Add("exp", Math.Exp);
}
public double Evaluate(string f, double x) //Let's just assume that the specified function exists
{
return functions[f](x);
}
Florian Rappl, MVP Visual C#