Lambda expression without declaration?

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 a delegate?

Well, since I think that Declaration is not the correct word, I will write the code how 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 this?
I want to reduce the complexity if the conditions are in one expression. But I don't want to bloat my class or add some kind of helper / everything as it won't be used in another scope.

+3


source to share


2 answers


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

No, it is not possible to create a lambda expression without the first type declaration. Delegates are like any other object in C #: it must be of a well-defined type before you can assign a value to it.

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

For example, if you have a delegate that takes 0 to 16 parameters, you can use one of the delegation types Action

:

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 delegate types Func

:

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 many more: every control event in Windows Forms or WPF uses a predefined delegate type, usually EventHandler

or RoutedEventHandler

or some derivatives. There are specialized versions Func

such as Predicate

(although this is mostly a LINQ preface and is mostly outdated).

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

+6


source


You are looking for delegates Func<*>

:



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

      

0


source







All Articles