In C#, can you make a class visible only within its own namespace without living in a different assembly? This seems useful for typical helper classes that shouldn't be used elsewhere. (i.e. what Java calls package-private classes)
You can only restrict the access to the assembly containing the class using the internal modifier. You could also restrict the access to the class to a single class by making the class a nested class. E.g. if you make class B a private nested class in class A, B will only be accessible by A.
If you force to create a private class in Namespace, compiler will throw a compile time error "Namespace elements cannot be explicitly declared as private, protected or protected internal" . There are only two valid declarations for a class at the namespace level, "Internal" and "Public".
Two classes with the same name can be created inside 2 different namespaces in a single program. Inside a namespace, no two classes can have the same name. In C#, the full name of the class starts from its namespace name followed by dot(.)
The visibility of a class, a method, a variable or a property tells us how this item can be accessed. The most common types of visibility are private and public, but there are actually several other types of visibility within C#.
You can make the classes internal
but this only prevents anyone outside of the assembly from using the class. But you still have to make a separate assembly for each namespace that you want to do this with. I'm assuming that is why you wouldn't want to do it.
Getting the C# Compiler to Enforce Namespace Visibility
There is an article here (Namespace visibility in C#) that shows a method of using partial classes as a form of "fake namespace" that you might find helpful.
The author points out that this doesn't work perfectly and he discusses the shortcomings. The main problem is that C# designers designed C# not to work this way. This deviates heavily from expected coding practices in C#/.NET, which is one of the .NET Frameworks greatest advantages.
It's a neat trick… now don't do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With