What's the difference when we define delegate in the class or out of
it
When you define a delegate outside the class, and in no other class, it belongs to the namespace it was defined on. This means that if one wanted to use this delegate, the full path to it would look like this:
namespace ConsoleApplication1
{
class Program
{
static void H()
{
MyDelegate.Calculate y = (x, w) => 1;
}
}
}
namespace MyDelegate
{
public delegate int Calculate(int value1, int value2);
class Program
{
static void Main(string[] args)
{
}
}
}
As opposed if you were to expose it inside a class, your path would contain the actual class that defined the delegate:
namespace ConsoleApplication1
{
class Program
{
static void H()
{
MyDelegate.Program.Calculate y = (x, w) => 1;
}
}
}
namespace MyDelegate
{
class Program
{
public delegate int Calculate(int value1, int value2);
static void Main(string[] args)
{
}
}
}
Edit:
As @MatthewWatson points out in the comments, as delegate
is a type, it should usually be declared at the namespace level, like Action<T>
and Func<T>
are in the .NET framework. If you want to implement a delegate which will internally be used inside a class hierarchy, you could potentially place it inside the class and set it as protected
. I do recommend using the delegates mentioned above which are exposed by the .NET framework and fulfill most requirements.