Daniel
Daniel

Reputation: 7724

C# make class invisible to all namespaces other than its own

Suppose I have the namespace Events, which contains only the classes EventManager and EventType.

I want EventType to be invisible in any other namespace, the only class who should be able to see EventType is EventManager.

How can I do this? I read something about Friend but still don't know it is the right choice.

Upvotes: 0

Views: 345

Answers (1)

Kit
Kit

Reputation: 21709

You expressed two "wants" in this XY Problem (at the same time) statement:

I want EventType to be invisible in any other namespace, the only class who should be able to see EventType is EventManager.

For the first part (X), as mentioned in the comments, there is no way to limit access to a class to only a single namespace directly in C#. You can kind of get what you want if you make it internal and isolate it in an assembly containing only that namespace.

That seems like a dubious practice however, and as you go about adding code you'll probably wind up abandoning this approach.

For the second part (Y), you can make EventType only visible to EventManager (this is your true intent) like this

public class EventManager
{
     private class EventType
     { ... }
}

The friend idea comes from C++ by the way.

Upvotes: 3

Related Questions