This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Learn how to write lambda expressions in C#.
This video doesn't have any notes.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Now that we've got a working console
application, let's refactor it
0:00
even more with a C# language
feature called Lambda Expressions.
0:04
We can use Lambda Expressions to
represent our anonymous methods.
0:09
Lambda Expressions can be a little
daunting when you first see one, but
0:13
as we practice they will
start to feel more natural.
0:17
We'll be using a new operator
called the Lambda Operator.
0:20
Lambdas originate from math.
0:25
Mathematicians needed a simple
way to represent a computation,
0:27
functional programmers thought
it was a great idea and
0:31
incorporated the syntax
into their languages.
0:34
Since we're not here to learn about math,
0:37
let's dive into how a lambda
expression is written in C#.
0:39
Lambda Expressions consist of one or
0:44
more input parameters,
a Lambda Operator and an Expression.
0:47
So, we can write a simple
Lambda like this.
0:52
What does that mean?
0:56
We've got an input parameter,
the x in parentheses, a lambda operator,
0:58
the equal sign followed by a greater
than sign, and an expression, x + 2.
1:03
If I were to explain this to someone in
conversation, I would say x goes to x + 2.
1:09
Whenever we see the lambda operator
we can use the phrase goes to.
1:16
So if x had a value of one at
the time this function ran,
1:21
the expression would evaluate to three.
1:24
Let's take the functions we
wrote earlier and lambdify them.
1:29
Let's start with our conversate function.
1:32
We don't need the delegate
keyword anymore, and
1:35
we also don't need to declare
a message as a string.
1:38
The compiler can infer what type it is
by looking at the types here in our
1:42
declaration.
1:46
Message goes to.
1:47
We can also turn our say greeting
action down here into a lambda.
1:48
In fact, why don't you pause the video and
1:55
try it yourself before
watching how I do it.
1:57
Okay, here's how I would do it.
2:02
Delete the delegate, delete string,
and add a lambda operator.
2:05
So say greeting = greeting => and
then our WriteLine.
2:12
Let's see if this works,
2:19
mcs Program.cs and mono Program.exe.
2:24
What you name, Carling.
2:30
Hello, Carling.
2:33
Nice to see you!
2:33
You too!
2:34
Are you doing well?
2:36
Yep!
2:37
Later Carling!
2:38
Great, now we've got lambdas.
2:39
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up