2

I am new to Linq and Delegates and all that an I have following issue:

I tried this:

Func<int> f = () => { return 123; };

Delegate t = f;

Visual Studio shows no errors but then I try this:

Delegate d = () => return 123;

It's not working

Then I tried this:

Action a = delegate { Console.Out.WriteLine("test"); };
Delegate x = a;

It works, but

Delegate j = delegate { Console.Out.WriteLine("test"); };

Directly casting seems not to work. Why?

Can somebody explain me please the differences between Delegate (first cap letter) and delegate (all small letters) and Func<> and Action?

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
dev hedgehog
  • 8,698
  • 3
  • 28
  • 55
  • Related: [Delegate vs. delegate keyword](https://stackoverflow.com/questions/779021/delegate-vs-delegate-keyword) – sloth Apr 16 '14 at 12:33
  • possible duplicate of [Cannot convert lambda expression to type 'System.Delegate'](http://stackoverflow.com/questions/9549358/cannot-convert-lambda-expression-to-type-system-delegate) – Rawling Apr 16 '14 at 12:37

1 Answers1

3

You are missing fact that:

Func<int> f = () => { return 123; };
Delegate t = f;

is in fact using constructor:

Func<int> f = new Func<int>(() => { return 123; });

But there is no Delegate constructor taking lambda expression or implicit conversion between them.

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
  • Ok why does then Delegate t has no Invoke() method but Func has Invoke()? What is the difference there? – dev hedgehog Apr 16 '14 at 12:52
  • Can you source this fact? – Rawling Apr 16 '14 at 12:58
  • @devhedgehog t has DynamicInvoke(), whild f has Invoke() and DynamicInvoke : see http://stackoverflow.com/questions/12858340/difference-between-invoke-and-dynamicinvoke – Raphaël Althaus Apr 16 '14 at 13:04
  • But if I can do this: Delegate t = f; then why I do need dynamic Invoke when I already know its function and I know the types. What am I missing? – dev hedgehog Apr 16 '14 at 13:09
  • If the compiler has to wrap a lambda in a `Func` constructor to assign it to a `Func`, *how does it convert the lambda to a `Func` to pass to the constructor*? – Rawling Apr 16 '14 at 13:15
  • @devhedgehog `Delegate t = f` Then you can do `((Func)t).Invoke()`. But Delegate class simply doesn't have an Invoke method. see http://msdn.microsoft.com/en-us/library/vstudio/system.delegate_methods(v=vs.110).aspx – Raphaël Althaus Apr 16 '14 at 13:36
  • What type is Func how can I find the source code of Invoke? – dev hedgehog Apr 16 '14 at 13:44