tags:

views:

85

answers:

2

Sorry if this question is too simple or easy.

I just started studying Delegates using C#. When I tried to declare one inside a function I got design time errors, but when I declare the same Delegate at class level, it works fine. Why?

If matters this is the code: delegate void Test();

+8  A: 

AFAIK, declaring a delegate like that (in C#, which I assume is the language you are using) is declaring a new type. Just as you cannot declare classes, structs, or interfaces in a method, you cannot declare this type.

Edit: If you're just learning delegates, and the language is indeed c#, consider using the Func templated delegate! It will save you from having declarations everywhere.

http://msdn.microsoft.com/en-us/library/bb549151.aspx

Stefan Valianu
Second the look at Func<> and Action<>. If you're looking for delegate-like functionality inside a method, these are the way to go. There's no use case for an actual delegate to be created inside a method.
drharris
A: 

Defining a delegate within a function would essentially be declaring a function within a function. The intention of delegates is to pass them between functions/methods, so they are only useful when declared at the class level.

Dave Swersky