3

An example for Lambda expressions from MSDN

delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}

Is it possible to do the same, without declaring the delegate?

Well since I think declaring is not the right word, I'll write the code as I would like to do it

static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}


Why do I want to do that?
I want to reduce complex if conditions into a single expression. But I don't want to bloat my class or add some kind of helper class / whatever since it won't be used in another scope.

1

2 Answers 2

6

Is it possible to do the same, without declaring the delegate?

No, it's not possible to create a lambda expression without first declaring a type. Delegates are like any other object in C#: it must have a well-defined type before you can assign it a value.

However, you may not need to declare the types yourself, because Microsoft has declared a ton of them for you. If one of the predefined delegate types works for you, feel free to use those.

For example, if you have a delegate that takes anywhere from 0 through 16 parameters, you can use one of the Action delegate types:

Action x = () => DoStuff();
Action<int> x = i => DoStuff(i);
Action<string, string, string> = (a,b,c) => DoStuff(a,b,c);

If you need to return a value, you can use one of the Func delegate types:

Func<int> x = () => 6;
Func<int, int> x = i => i * i;
Func<string, string, string, string> x = (a,b,c) => a.Replace(b, c);

etc.

There are tons more of them: every control event in Windows Forms or WPF uses a pre-defined delegate type, usually of EventHandler or RoutedEventHandler or some derivate. There are specialized version of Func such as Predicate (though those largely pre-date LINQ and are mostly obsolete).

But, if for some odd reason none of the built-in delegate types works for you, then yes, you need to define your own before you can use it.

Sign up to request clarification or add additional context in comments.

1 Comment

Well - excellent answer. Thanks for your explanation. Unfortunately I just can give a single +1 ;)
-1

You're looking for the Func<*> delegates:

Func<int, int> myDelegate = ...;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.