views:

116

answers:

4

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();
+2  A: 

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

jim
+2  A: 

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.

Josh Smeaton
+5  A: 

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);
lasseespeholt
+2  A: 

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;
SWeko