Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of a delegate in C#

Can delegates be private? If not, what's the reason behind this other than the normal restrictions caused by it being private?

like image 337
SoftwareGeek Avatar asked Feb 14 '10 02:02

SoftwareGeek


1 Answers

Delegates have the same restrictions as any type with regards to visibility. So you cannot have a private delegate at the top level.

namespace Test
{
    private delegate void Impossible();
}

This generates a compiler error:

Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

But like a class, you can declare a delegate private when it resides within another class.

namespace Test
{
    class Sample
    {
        // This works just fine.
        private delegate void MyMethod();

        // ...
    }
}

The reason basically goes back to the definition of what private is in C#:

private | Access is limited to the containing type.

like image 191
bobbymcr Avatar answered Oct 08 '22 18:10

bobbymcr