1

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();
Evernoob
  • 5,551
  • 8
  • 37
  • 49
Thomas
  • 2,575
  • 9
  • 31
  • 41

4 Answers4

5

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);
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
2

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 tollan
  • 22,305
  • 4
  • 49
  • 63
2

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
  • 47,939
  • 24
  • 129
  • 164
2

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
  • 30,434
  • 10
  • 71
  • 106