C# LINQ Background Topics

player_one
2,120 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Delegates - Delegate variables

Referring to the FuncTwoInts type, previously declared as:

private delegate int FuncTwoInts(int one, int two);

Delegate expressions

The FuncTwoInts type can be used to declare variables like this:

private static int Add(int one, int two)
{
    return one + two;
}

private FuncTwoInts theFunc = Add;

Or like this:

FuncTwoInts theFunc = delegate (int one, int two)
{
    return one + two;
};

Or this:

FuncTwoInts theFunc = (one, two) =>
{
    return one + two;
};

Or even like this:

FuncTwoInts theFunc = (one, two) => one + two;

Lambda expressions

The last two delegate examples above (the ones utilizing the => operator) are called lambda expressions. Lambda expressions are just a more efficient way of defining a delegate.

NOTE: The => operator is called the lambda operator.

If the function defined by the lambda expression is more than a single line, then the { } are required, as is the return keyword. On the other hand, if the only statement in the lambda expression is the return statement, then the second, abbreviated form can be used.

Exercise

In this exercise, you must use either a method delegate or a lambda expression to define the HelloFunc variable such that it produces the desired results. The required delegate takes a single string argument and returns a string result.

Delegate Variable Exercise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace Delegates2
{
public delegate string SayHello(string subject);
public static class DelegatesExercise2
{
// Uncomment the declaration of HelloFunc
//
// Utilizing one of the techniques for defining a
// delegate function, define HelloFunc such that
// when given a string "foo" as a parameter, it
// will return the string "Hello, foo!".
//
// Try to solve this exercise utilizing different
// techiniques for defining a delegate, as shown
// in the lesson.
// public static readonly SayHello HelloFunc = ???
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content