In Javascript, you can create an anonymous function (function literal) in
one statement:
c = function(x,y){return x * y}; // define and assign in one line (how
poetic)
alert ("c = " + c(10,20)); // use it here.
But in C# it seems you need to use 2 lines - one being a delegate - to
accomplish the same thing.
delegate int Multiply(int x, int y); // 1st define and give it
a name (so not anonymous, really).
// Also, it
seems to need to be defined outside of a function
// so global.
Multiply c = delegate(int x, int y) { return x * y; }; // 2nd
define - define the function and assign it
Console.WriteLine("c = " + c(10, 20)); // use it here.
Is this correct?
Just trying to get the similarities straight.
Thanks,
Tom
cpp.mbs@gmail.com - 31 Mar 2008 08:44 GMT
Hi,
yes, its correct. In Net 3.5 you can also use the predefined system
delegate Func<> and write it in two lines:
Func<int, int, int> multiply = (x, y) => x * y;
Console.WriteLine(multiply(10, 20));
Jon Skeet [C# MVP] - 31 Mar 2008 08:53 GMT
> In Javascript, you can create an anonymous function (function literal) in
> one statement:
[quoted text clipped - 5 lines]
> But in C# it seems you need to use 2 lines - one being a delegate - to
> accomplish the same thing.
Well, there has to *be* an appropriate delegate type somewhere, yes. As
the other respondent replied, the Func family of delegates in .NET 3.5
means you very rarely need to declare your own delegate types any more
- but even pre-.NET 3.5 there were some fairly general purpose delegate
types (e.g. EventHandler<T> and Action<T>).

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Ignacio Machin ( .NET/ C# MVP ) - 31 Mar 2008 15:56 GMT
> In Javascript, you can create an anonymous function (function literal) in
> one statement:
[quoted text clipped - 23 lines]
>
> Tom
Hi,
That is true only in the case that a delegate does not exist already.
Remember Javascript is not strong typed. C# is.
tshad - 31 Mar 2008 16:36 GMT
>> In Javascript, you can create an anonymous function (function
>> literal) in one statement:
[quoted text clipped - 27 lines]
> That is true only in the case that a delegate does not exist already.
> Remember Javascript is not strong typed. C# is.
That makes sense.
So in Javascript you are not defining a type, but in C# you need a type for
the variable you are assigning the function to. The first line then defines
the type (which includes the parameters).
Then you have to redefine the parameters which the actual method code, but
there is no name for the function (method) itself.
Thanks,
Tom