0

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.

Daniel
  • 7,357
  • 7
  • 32
  • 84
  • There is no access-modifier in c# restricting to a namespace. You can only declare the type as `internal` to restrict visibility to the containing assembly. – René Vogt May 15 '18 at 16:15
  • I find your assignment of gender to a class interesting. – STLDev May 15 '18 at 16:17
  • 1
    not sure entirely what your going for, but if you make EventType a sub/nested class in event manager you can make it Protected to keep other classes from using it i believe. https://stackoverflow.com/questions/1017778/protected-classes-in-net goes into more detail. – Hack May 15 '18 at 16:21
  • 3
    You can make `EventType` a private class inside the `EventManager` class – maccettura May 15 '18 at 16:21
  • @STLDeveloper: in French I believe it is _"la classe"_ - so feminine – PaulF May 15 '18 at 16:22

1 Answers1

3

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.

Kit
  • 20,354
  • 4
  • 60
  • 103