Hi, Why can't I have this? I mean it would spare a delegate declaration:
int X=delegate int(){...};
I know it can be done this way:
delegate int IntDelegate();
...
IntDelegate del=delegate(){return 25;};
int X=del();
Hi, Why can't I have this? I mean it would spare a delegate declaration:
int X=delegate int(){...};
I know it can be done this way:
delegate int IntDelegate();
...
IntDelegate del=delegate(){return 25;};
int X=del();
Tomas,
would this work for you:
delegate int IntDelegate();
// other stuff...
IntDelegate _del = () => 25;
jim
[edit] - oops, just realised, the question was re making it a one liner!! - i'll have a think
Because in the first example, you're trying to assign a delegate type into an int, rather than the output of a delegate into an int. A delegate is a type that stores a function, which just so happens to return a value that you're interested in.
A delegate is not an int.
If you use .Net 3.5 or newer you can use the built in Func instead of using a custom (Func also have generic types if you need arguments like Func which tages a string and return an int):
Func<int> X = delegate() { return 255; };
or with lambda expressions:
Func<int> X = () => 255;
Unfortunately, you can't say:
var X2 = () => 255;
in C# but you can do something similar in functional languages ex F#. Instead you would say the following in C#:
var X2 = new Func<int>(() => 255);
Is there really a need for creating a delegate, executing it, and returning the value? Why not just execute the code directly?
int x = new Func<int,int>(num => num*num) (3);
would return 9, but so would:
int x = 3*3;