SoftwareGeek
SoftwareGeek

Reputation: 15772

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?

Upvotes: 6

Views: 3299

Answers (1)

bobbymcr
bobbymcr

Reputation: 24167

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.

Upvotes: 16

Related Questions