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.