Why can't I declare a delegate at the function level?

Sorry if this question is too simple or simple.

I just started learning 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 the class level, it works fine. Why?

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

+4
source share
2 answers

AFAIK, declaring such a delegate (in C #, which I assume is the language you use) declares a new type. Just as you cannot declare classes, structures, or interfaces in a method, you cannot declare this type.

Edit: if you are just learning delegates, and the language is really C #, consider using the Func templated delegate! This will save you from all ads.

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

+8
source

A delegate definition inside a function will essentially declare a function inside a function. The goal of delegates is to pass them between functions / methods, so they are only useful when declaring at the class level.

0
source

Source: https://habr.com/ru/post/1313216/


All Articles