Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Multiple Namespaces for single class

Tags:

Is it possible to have a single class reside within two name-spaces and how can I do this?

To clarify: We have a class library (let say root namespace is classLib1), which has grown over time (more classes) and I want to logically group classes into different namespaces. However some of the older classes need to be grouped into these new namespaces (e.g classLib1.section1) and doing so will break legacy code in other assemblys that use this class library. So I want to be able to refer to a class using both name-spaces until we can phase the old ones out.

I can't find any information on this, which suggests there is a reason that people would not want to do this!?!

like image 518
Mr Shoubs Avatar asked Sep 27 '10 15:09

Mr Shoubs


People also ask

Can a class have multiple namespaces?

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.

Can I use multiple namespaces in C#?

In c#, we can define and access multiple namespaces in our application with using keyword. To access the custom namespace classes, we need to import the custom namespace with using keyword and need to create an instance for that classes in our application.

How do you call a class from another namespace in C#?

If you need to access a variable in another class (in another namespace), your other class needs to expose the variable somehow. The common practice for this is to use a public Property (static if you only need access to that variable) for the variable.

Is namespace mandatory in C#?

There is no need to have a namespace. However developer studio expects you to be using a name space. For example, when you choose to add a class to a project developer studio will: Create a file for the class.


1 Answers

No, there is no way to give a single class two names (the namespace is actually just a part of the class name).

As a workaround, you could move the classes to their new location, and create thin wrappers around them at the old location (Facade Pattern). A better solution, of course, would be to move the classes and fix the legacy code accordingly.

like image 84
dtb Avatar answered Sep 26 '22 00:09

dtb