Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace-only class visibility in C#/.NET?

Tags:

c#

.net

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)

like image 620
nos Avatar asked Aug 03 '09 18:08

nos


People also ask

How do you make a class accessible only within the namespace?

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.

Can we create private class in namespace?

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".

Can namespace and class have same name?

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(.)

What is class visibility in C#?

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#.


1 Answers

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.

like image 154
Robert Cartaino Avatar answered Oct 04 '22 11:10

Robert Cartaino