boop
boop

Reputation: 7788

Lambda expression without declaration?

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.

Upvotes: 3

Views: 508

Answers (2)

Michael Edenfield
Michael Edenfield

Reputation: 28338

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.

Upvotes: 6

SLaks
SLaks

Reputation: 887657

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

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

Upvotes: -1

Related Questions