Building Linq expressions - c#

I can easily build any linq expression without using Expression factory methods. for example:
Func<int, string> f = i =>
{
var result = i.ToString();
//... rest of the code
return result;
};
Expression<Func<string>> f2 = () => f(123);
var s = f2.Compile()();
What's the advantage of building the expression manually by calling factory methods?

Examples:
you are building the query based on reflection of a model you don't know about in advance
you are building the query based on input, i.e. parsing a string "(a.b + c) * 7"
you are composing multiple expressions into a single expression (visitor pattern, maybe)
you are doing things that can't be validly expressed via lambdas, i.e. statement bodies, member-assignment, etc (which are available in .NET 4.0, but not via the lambda compiler)
you are using a language/version that doesn't have a lambda compiler
you want fine-grained control over the lambda construction (i.e. what is a constant, what is captured, etc)
you just want to learn how it all works

Related

How ToDictionary in c# works? [duplicate]

I have quickly read over the Microsoft Lambda Expression documentation.
This kind of example has helped me to understand better, though:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?
Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.
The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:
// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();
// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();
Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects.
Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:
void Example(Predicate<int> aDelegate);
called like:
Example(x => x > 5);
becomes:
void Example(Expression<Predicate<int>> expressionTree);
The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.
Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.
Consider this example:
List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };
string person = people.Find(person => person.Contains("Joe"));
versus
public string FindPerson(string nameContains, List<string> persons)
{
foreach (string person in persons)
if (person.Contains(nameContains))
return person;
return null;
}
These are functionally equivalent.
I found them useful in a situation when I wanted to declare a handler for some control's event, using another control.
To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.
private ComboBox combo;
private Label label;
public CreateControls()
{
combo = new ComboBox();
label = new Label();
//some initializing code
combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}
void combo_SelectedIndexChanged(object sender, EventArgs e)
{
label.Text = combo.SelectedValue;
}
thanks to lambda expressions you can use it like this:
public CreateControls()
{
ComboBox combo = new ComboBox();
Label label = new Label();
//some initializing code
combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}
Much easier.
Lambda's cleaned up C# 2.0's anonymous delegate syntax...for example
Strings.Find(s => s == "hello");
Was done in C# 2.0 like this:
Strings.Find(delegate(String s) { return s == "hello"; });
Functionally, they do the exact same thing, its just a much more concise syntax.
This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
strings.Find(s => s == "hello");
This code will search the list for an entry that matches the word "hello". The other way to do this is to actually pass a delegate to the Find method, like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
private static bool FindHello(String s)
{
return s == "hello";
}
strings.Find(FindHello);
EDIT:
In C# 2.0, this could be done using the anonymous delegate syntax:
strings.Find(delegate(String s) { return s == "hello"; });
Lambda's significantly cleaned up that syntax.
Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:
using System;
using System.Linq;
using System.Linq.Expressions;
namespace ExpressionTreeThingy
{
class Program
{
static void Main(string[] args)
{
Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
Console.WriteLine(del(5)); //we are just invoking a delegate at this point
Console.ReadKey();
}
}
}
This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.
It saves having to have methods that are only used once in a specific place from being defined far away from the place they are used. Good uses are as comparators for generic algorithms such as sorting, where you can then define a custom sort function where you are invoking the sort rather than further away forcing you to look elsewhere to see what you are sorting on.
And it's not really an innovation. LISP has had lambda functions for about 30 years or more.
You can also find the use of lambda expressions in writing generic codes to act on your methods.
For example: Generic function to calculate the time taken by a method call. (i.e. Action in here)
public static long Measure(Action action)
{
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
return sw.ElapsedMilliseconds;
}
And you can call the above method using the lambda expression as follows,
var timeTaken = Measure(() => yourMethod(param));
Expression allows you to get return value from your method and out param as well
var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));
Lambda expression is a concise way to represent an anonymous method. Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method. Lambda expression uses the type inference feature of C# 3.0 which allows the compiler to infer the type of the variable based on the context. It’s is very convenient because that saves us a lot of typing!
A lambda expression is like an anonymous method written in place of a delegate instance.
delegate int MyDelagate (int i);
MyDelagate delSquareFunction = x => x * x;
Consider the lambda expression x => x * x;
The input parameter value is x (on the left side of =>)
The function logic is x * x (on the right side of =>)
A lambda expression's code can be a statement block instead of an expression.
x => {return x * x;};
Example
Note: Func is a predefined generic delegate.
Console.WriteLine(MyMethod(x => "Hi " + x));
public static string MyMethod(Func<string, string> strategy)
{
return strategy("Lijo").ToString();
}
References
How can a delegate & interface be used interchangeably?
A lot of the times, you are only using the functionality in one place, so making a method just clutters up the class.
It's a way of taking small operation and putting it very close to where it is used (not unlike declaring a variable close to its use point). This is supposed to make your code more readable. By anonymizing the expression, you're also making it a lot harder for someone to break your client code if it the function is used somewhere else and modified to "enhance" it.
Similarly, why do you need to use foreach? You can do everything in foreach with a plain for loop or just using IEnumerable directly. Answer: you don't need it but it makes your code more readable.
The innovation is in the type safety and transparency. Although you don't declare types of lambda expressions, they are inferred, and can be used by code search, static analysis, refactoring tools, and runtime reflection.
For example, before you might have used SQL and could get an SQL injection attack, because a hacker passed a string where a number was normally expected. Now you would use a LINQ lambda expression, which is protected from that.
Building a LINQ API on pure delegates is not possible, because it requires combining expression trees together before evaluating them.
In 2016 most of the popular languages have lambda expression support, and C# was one of the pioneers in this evolution among the mainstream imperative languages.
The biggest benefit of lambda expressions and anonymous functions is the fact that they allow the client (programmer) of a library/framework to inject functionality by means of code in the given library/framework ( as it is the LINQ, ASP.NET Core and many others ) in a way that the regular methods cannot. However, their strength is not obvious for a single application programmer but to the one that creates libraries that will be later used by others who will want to configure the behaviour of the library code or the one that uses libraries. So the context of effectively using a lambda expression is the usage/creation of a library/framework.
Also since they describe one-time usage code they don't have to be members of a class where that will led to more code complexity. Imagine to have to declare a class with unclear focus every time we wanted to configure the operation of a class object.
Lambda expression makes tasks much simpler, for example
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var oddNumbers = numbers.Where(x => x % 2 != 0);
var sumOfEven = numbers.Where(x => x % 2 == 0).Sum();
In the above code, because we are using lambda, we are getting odd number and sum of even numbers in single line of code.
Without lambda, we will have to use if/else or for loop.
So it is good to use lambda to simplify code in C#.
Some articles on it:
https://qawithexperts.com/article/c-sharp/lambda-expression-in-c-with-examples/470
https://exceptionnotfound.net/csharp-in-simple-terms-18-expressions-lambdas-and-delegates
http://dontcodetired.com/blog/post/Whats-New-in-C-10-Easier-Lambda-Expressions
In C# we cannot pass functions as parameters like we do in JavaScript. The workaround is using delegates.
When we want to parameterize the behavior instead of a value, we use delegates. Lambdas are practical syntax for writing delegates which makes it very easy to pass around behavior as functions.
This is perhaps the best explanations on why to use lambda expressions -> https://youtu.be/j9nj5dTo54Q
In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes.

What's the purpose of the Expression class?

I'm wondering what exactly is the difference between wrapping a delegate inside Expression<> and not ?
I'm seeing Expression<Foo> being used a lot with LinQ, but so far I've not found any article that explains the difference between this, and just using a delegate.
E.g.
Func<int, bool> Is42 = (value) => value == 42;
vs.
Expression<Func<int, bool>> Is42 = (value) => value == 42;
tl;dr, To have an expression is like having the source code of an application, and a delegate is an executable to run the application. An expression can be thought of as the "source" (i.e., syntax tree) of the code that would run. A delegate is a specific compilation that you would run and does the thing.
By storing a lambda as a delegate, you are storing a specific instance of a delegate that does some action. It can't be modified, you just call it. Once you have your delegate, you have limited options in inspecting what it does and whatnot.
By storing a lambda as an expression, you are storing an expression tree that represents the delegate. It can be manipulated to do other things like changing its parameters, changing the body and make it do something radically different. It could even be compiled back to a delegate so you may call it if you wish. You can easily inspect the expression to see what its parameters are, what it does and how it does it. This is something that a query provider can use to understand and translate an expression to another language (such as write an SQL query for a corresponding expression tree).
It is also a whole lot easier to create a delegate dynamically using expressions than it is emitting the code. You can think of your code at a higher level as expressions that is very similar to how a compiler views code instead of going low-level and view your code as IL instructions.
So with an expression, you are capable to do much more than a simple anonymous delegate. Though it's not really free, performance will take a hit if you run compiled expressions compared to a regular method or an anonymous delegate. But that might not be an issue as the other benefits to using expressions may be important to you.
Func<> is just a delegate type. An Expression is a runtime representation of the complete tree of operations which, optionally, may be compiled at runtime into a delegate. It's this tree that is parsed by Expression parsers like Linq-to-SQL to generate SQL statements or do other clever things. When you assign a lambda to an Expression type, the compiler generates this expression tree as well as the usual IL code. More on expression trees.
To illustrate other answers, if you compile those 2 expressions and have look at the compiler generated code, this i what you will see:
Func<int, bool> Is42 = (value) => value == 42;
Func<int, bool> Is42 = new Func<int, bool>((#value) => value == 42);
Expression<Func<int, bool>> Is42 = (value) => value == 42;
ParameterExpression[] parameterExpressionArray;
ParameterExpression parameterExpression = Expression.Parameter(typeof(int), "value");
Expression<Func<int, bool>> Is42 = Expression.Lambda<Func<int, bool>>(Expression.Equal(parameterExpression, Expression.Constant(42, typeof(int))), new ParameterExpression[] { parameterExpression });
Expression Trees allow you to inspect the code inside the expression, in your code.
For example, if you passed this expression: o => o.Name, your code could find out that the Name property was being accessed inside the expression.
Provides the base class from which the classes that represent
expression tree nodes are derived.
System.Linq.Expressions.BinaryExpression
System.Linq.Expressions.BlockExpression
System.Linq.Expressions.ConditionalExpression
System.Linq.Expressions.ConstantExpression
System.Linq.Expressions.DebugInfoExpression
System.Linq.Expressions.DefaultExpression
System.Linq.Expressions.DynamicExpression
System.Linq.Expressions.GotoExpression
System.Linq.Expressions.IndexExpression
System.Linq.Expressions.InvocationExpression
System.Linq.Expressions.LabelExpression
System.Linq.Expressions.LambdaExpression
System.Linq.Expressions.ListInitExpression
System.Linq.Expressions.LoopExpression
System.Linq.Expressions.MemberExpression
System.Linq.Expressions.MemberInitExpression
System.Linq.Expressions.MethodCallExpression
System.Linq.Expressions.NewArrayExpression
System.Linq.Expressions.NewExpression
System.Linq.Expressions.ParameterExpression
System.Linq.Expressions.RuntimeVariablesExpression
System.Linq.Expressions.SwitchExpression
System.Linq.Expressions.TryExpression
System.Linq.Expressions.TypeBinaryExpression
System.Linq.Expressions.UnaryExpression
http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx
Expression tree represents linq expression that can be analyzed and for example turned into SQL query.
To whatever the other wrote (that is completely correct) I'll add that through the Expression class you can create new methods at runtime. There are some limits. Not all the things you can do in C# can be done in an Expression tree (at least in .NET 3.5 . With .NET 4.0 they have added a great number of possible Expression "types"). The use of this could be (for example) to create a dynamic query and pass it to LINQ-to-SQL or do some filtering based on the input of the user... (you could always do this with CodeDom if all you wanted was a dynamic method incompatible with LINQ-to-SQL, but emitting directly IL code is quite difficult :-) )

Trying to understand what an expression tree is

Both snippets below product the same output.
I understand how Func encapsulates a method with a single parameter, and returns a bool value. And you can either assign it a
method, anonymous method or a lambda expression.
Func<int, bool> deleg = i => i < 5;
Console.WriteLine("deleg(4) = {0}", deleg(4));
Below is using expression trees which I don't fully understand yet. Why would I want to do it this way? Is it more flexible, what advantage does it give me?
System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5;
Func<int, bool> deleg2 = expr.Compile();
Console.WriteLine("deleg2(4) = {0}", deleg2(4));
Basically, the Expression tree is the body of a lambda expression, that allows you to
introspect the expression (see what's in it so to say)
manipulate the expression (simplify, extend (e.g. add new functionality or modify to work on different items).
Once you Compile() the expression, it is just another delegate, which you can only call, not inspect or modify.
Whenever you want to
create expressions dynamically (I mean: construct, not allocate)
operate on expressions dynamically
the Function<> types are not sufficient.
The point of expression trees is that you can do more with them than just compile them to a function. You can inspect them, modify them and compile them to something other than .net functions.
For example Linq2SQL compiles expression trees to SQL code. You couldn't do that with a plain .net function.
In your first example you just have "hardcoded" the body of the function and assigned it to a delegate.
In your second example the assignment constructs an expression-tree which is an object model reprensenting your code in a data structure in memory.
The advantage is that you can modify and inspect that datastructure.
LINQ2SQL for example uses that technique to translate your expressions to another language called SQL.
Expression trees are regular in-memory data structures that can be traversed programmatically and the result of such traversal can be something, like a query you'd like to send to the database. Read more on the ExpressionVisitor class to see how it is done.
On the other hand, the compiled function is nothing more than a sequence of CIL code. You still can inspect it programmatically but you are not inspecting the definition but rather - the compiler output of it.

difference between Expression and Func

What is the difference between Expression and Func? The same task can be attained by both. So what is the difference?
Expression trees are data representations of logic - which means they can be examined at execution time by things like LINQ providers. They can work out what the code means, and possibly convert it into another form, such as SQL.
The Func family of types, however, are just delegates. They end up as normal IL, which can be executed directly, but not (easily) examined. Note that you can compile expression trees (well, Expression<T> and LambdaExpression) into delegates and execute those within managed code as well, if you need to.
You can build up expression trees manually using the factory methods in the Expression class, but usually you just use the fact that C# can convert lambda expressions into both expression trees and normal delegates:
Expression<Func<int, int>> square = x => x * x;
Func<int, int> square = x => x * x;
Note that there are limitations on which lambda expressions can be converted into expression trees. Most importantly, only lambdas consisting of a single expression (rather than a statement body) can be converted:
// Compile-time error
Expression<Func<int, int>> square = x => { return x * x; };
// Works fine
Func<int, int> square = x => { return x * x; };
It is not true that "they do the same thing". Expression describes your intent in a way that can be interpreted at runtime - it is, if you like, the recipe. A function is an opaque delegate, that can't be inspected - it can be used as a black box. Compared to a recipe, it is some kind of auto-chef that doesn't let you see what it does: give it some bread and some chicken, close your eyes and it gives you a sandwich, but you never get to know how.
I discuss this more here: Explaining Expression, but having the recipe is key for LINQ, RPC, etc. And of course, if you have the recipe you can make your own chef, via Expression.Compile().
Expression can be built at runtime, function not (unless you use reflection emit). Once you build the expression tree you can compile it and turn it into a function pointer which can be invoked. Func is a pointer to some already existing function which can no longer be modified while Expression represents the code of some function that doesn't exist until you compile it.
You usually use expressions when you want to preserve the semantics of the code so that you can translate it. That is, expressions allow you to treat the code as data. If the code does not need to be treated as data (i.e. you're not planning on storing it or translating it) then using a Func is appropriate.

C# Lambda expressions: Why should I use them?

I have quickly read over the Microsoft Lambda Expression documentation.
This kind of example has helped me to understand better, though:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?
Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL.
The following is an example of a LINQ to Objects expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:
// anonymous delegate
var evens = Enumerable
.Range(1, 100)
.Where(delegate(int x) { return (x % 2) == 0; })
.ToList();
// lambda expression
var evens = Enumerable
.Range(1, 100)
.Where(x => (x % 2) == 0)
.ToList();
Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects.
Expression trees are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an Expression<T> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:
void Example(Predicate<int> aDelegate);
called like:
Example(x => x > 5);
becomes:
void Example(Expression<Predicate<int>> expressionTree);
The latter will get passed a representation of the abstract syntax tree that describes the expression x > 5. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.
Anonymous functions and expressions are useful for one-off methods that don't benefit from the extra work required to create a full method.
Consider this example:
List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };
string person = people.Find(person => person.Contains("Joe"));
versus
public string FindPerson(string nameContains, List<string> persons)
{
foreach (string person in persons)
if (person.Contains(nameContains))
return person;
return null;
}
These are functionally equivalent.
I found them useful in a situation when I wanted to declare a handler for some control's event, using another control.
To do it normally you would have to store controls' references in fields of the class so that you could use them in a different method than they were created.
private ComboBox combo;
private Label label;
public CreateControls()
{
combo = new ComboBox();
label = new Label();
//some initializing code
combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}
void combo_SelectedIndexChanged(object sender, EventArgs e)
{
label.Text = combo.SelectedValue;
}
thanks to lambda expressions you can use it like this:
public CreateControls()
{
ComboBox combo = new ComboBox();
Label label = new Label();
//some initializing code
combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}
Much easier.
Lambda's cleaned up C# 2.0's anonymous delegate syntax...for example
Strings.Find(s => s == "hello");
Was done in C# 2.0 like this:
Strings.Find(delegate(String s) { return s == "hello"; });
Functionally, they do the exact same thing, its just a much more concise syntax.
This is just one way of using a lambda expression. You can use a lambda expression anywhere you can use a delegate. This allows you to do things like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
strings.Find(s => s == "hello");
This code will search the list for an entry that matches the word "hello". The other way to do this is to actually pass a delegate to the Find method, like this:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
private static bool FindHello(String s)
{
return s == "hello";
}
strings.Find(FindHello);
EDIT:
In C# 2.0, this could be done using the anonymous delegate syntax:
strings.Find(delegate(String s) { return s == "hello"; });
Lambda's significantly cleaned up that syntax.
Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:
using System;
using System.Linq;
using System.Linq.Expressions;
namespace ExpressionTreeThingy
{
class Program
{
static void Main(string[] args)
{
Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
Console.WriteLine(del(5)); //we are just invoking a delegate at this point
Console.ReadKey();
}
}
}
This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.
It saves having to have methods that are only used once in a specific place from being defined far away from the place they are used. Good uses are as comparators for generic algorithms such as sorting, where you can then define a custom sort function where you are invoking the sort rather than further away forcing you to look elsewhere to see what you are sorting on.
And it's not really an innovation. LISP has had lambda functions for about 30 years or more.
You can also find the use of lambda expressions in writing generic codes to act on your methods.
For example: Generic function to calculate the time taken by a method call. (i.e. Action in here)
public static long Measure(Action action)
{
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
return sw.ElapsedMilliseconds;
}
And you can call the above method using the lambda expression as follows,
var timeTaken = Measure(() => yourMethod(param));
Expression allows you to get return value from your method and out param as well
var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));
Lambda expression is a concise way to represent an anonymous method. Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method. Lambda expression uses the type inference feature of C# 3.0 which allows the compiler to infer the type of the variable based on the context. It’s is very convenient because that saves us a lot of typing!
A lambda expression is like an anonymous method written in place of a delegate instance.
delegate int MyDelagate (int i);
MyDelagate delSquareFunction = x => x * x;
Consider the lambda expression x => x * x;
The input parameter value is x (on the left side of =>)
The function logic is x * x (on the right side of =>)
A lambda expression's code can be a statement block instead of an expression.
x => {return x * x;};
Example
Note: Func is a predefined generic delegate.
Console.WriteLine(MyMethod(x => "Hi " + x));
public static string MyMethod(Func<string, string> strategy)
{
return strategy("Lijo").ToString();
}
References
How can a delegate & interface be used interchangeably?
A lot of the times, you are only using the functionality in one place, so making a method just clutters up the class.
It's a way of taking small operation and putting it very close to where it is used (not unlike declaring a variable close to its use point). This is supposed to make your code more readable. By anonymizing the expression, you're also making it a lot harder for someone to break your client code if it the function is used somewhere else and modified to "enhance" it.
Similarly, why do you need to use foreach? You can do everything in foreach with a plain for loop or just using IEnumerable directly. Answer: you don't need it but it makes your code more readable.
The innovation is in the type safety and transparency. Although you don't declare types of lambda expressions, they are inferred, and can be used by code search, static analysis, refactoring tools, and runtime reflection.
For example, before you might have used SQL and could get an SQL injection attack, because a hacker passed a string where a number was normally expected. Now you would use a LINQ lambda expression, which is protected from that.
Building a LINQ API on pure delegates is not possible, because it requires combining expression trees together before evaluating them.
In 2016 most of the popular languages have lambda expression support, and C# was one of the pioneers in this evolution among the mainstream imperative languages.
The biggest benefit of lambda expressions and anonymous functions is the fact that they allow the client (programmer) of a library/framework to inject functionality by means of code in the given library/framework ( as it is the LINQ, ASP.NET Core and many others ) in a way that the regular methods cannot. However, their strength is not obvious for a single application programmer but to the one that creates libraries that will be later used by others who will want to configure the behaviour of the library code or the one that uses libraries. So the context of effectively using a lambda expression is the usage/creation of a library/framework.
Also since they describe one-time usage code they don't have to be members of a class where that will led to more code complexity. Imagine to have to declare a class with unclear focus every time we wanted to configure the operation of a class object.
Lambda expression makes tasks much simpler, for example
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var oddNumbers = numbers.Where(x => x % 2 != 0);
var sumOfEven = numbers.Where(x => x % 2 == 0).Sum();
In the above code, because we are using lambda, we are getting odd number and sum of even numbers in single line of code.
Without lambda, we will have to use if/else or for loop.
So it is good to use lambda to simplify code in C#.
Some articles on it:
https://qawithexperts.com/article/c-sharp/lambda-expression-in-c-with-examples/470
https://exceptionnotfound.net/csharp-in-simple-terms-18-expressions-lambdas-and-delegates
http://dontcodetired.com/blog/post/Whats-New-in-C-10-Easier-Lambda-Expressions
In C# we cannot pass functions as parameters like we do in JavaScript. The workaround is using delegates.
When we want to parameterize the behavior instead of a value, we use delegates. Lambdas are practical syntax for writing delegates which makes it very easy to pass around behavior as functions.
This is perhaps the best explanations on why to use lambda expressions -> https://youtu.be/j9nj5dTo54Q
In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes.

Categories

Resources