c# - Use alias in another file
Asked Answered
C

2

8

Is it possible to use an alias defined in one file throughout an assembly?

For eg. in Foo.cs I have

using IO = System.IO;
namespace Foo
{}

How can I use the alias "IO" in FooBar.cs

namespace Foo.Bar
{}
Clan answered 4/1, 2012 at 6:32 Comment(4)
What do you want to achieve ? You can add using IO = System.IO in every file you want..Krahmer
Adding this in every file is what I'm trying to avoid.Clan
possible duplicate of alias a namespace globaly for the entire projectPressurecook
Why do you want to avoid this ? If you want to reducre typing work you may create a templates for your class files.Krahmer
O
17

According to MSDN

The scope of a using directive is limited to the file in which it appears.

So the answer is No. You cannot define an alias in one file and use it throughout assembly

Orangutan answered 4/1, 2012 at 6:36 Comment(2)
A work around would be inheriting class IO : System.IO { }.Koral
@Koral can you write an example?Skeens
M
0

It would be nice to define global/shared using directive aliases. I recently considered this topic while working with a rather long class name across multiple files and methods.

One possibility to consider is using a code-generation tool that will add the alias to new files. This seems a bit pedantic however as it is pretty easy to just copy+paste the alias for every file that needs it.

Another option that one might consider is mentioned in hrzafer's comment:

A work around would be inheriting class IO : System.IO

Ignoring the bad syntax -- System.IO is a namespace and cannot be inherited by a class -- what hrzafer may have meant is something more like:

class Dir : System.IO.DirectoryInfo

Although this could work as a makeshift alias with simple classes, it could very well cause confusion since the point of inheritance is to reuse, extend, and modify the behavior defined in the base class.

Also, this approach doesn't work for sealed or static classes.

Mofette answered 27/3, 2022 at 2:17 Comment(1)
This really should have been a comment.Vergievergil

© 2022 - 2024 — McMap. All rights reserved.