Back
Close

C# LINQ Background Topics

player_one
13.9K views

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
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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants