Is it possible to define an alias for a class in .NET?

2.1k views Asked by At

The name of one of my classes was changed and I can't change it back. I have to mantain backwards compatibility and I don't want to write an wrapper with the old name. Is there any easy way to give a class 2 names or to give it an alias?

Lifted from a comment by the OP:

Don't tell me to use the using directive since it must be done in the consumer side, and I don't want to change the projects that are using my library.

2

There are 2 answers

2
LBushkin On BEST ANSWER

Arguably, your best option is to use a refactoring tool (like Resharper) to help you automate the conversion from the old name to the new name. However, if this is untenable to you for some reason, here are some alternatives:

If the types are in different assemblies you may be able to use a Type Forwarder. These allow you to redirect all references for a given type to an assembly ... but if IIRC, they can also redirect them to a new name as well.

Otherwise, within a single .cs source file you can apply a using statement:

using OldClassName = SomeNameSpace.NewClassName

This doesn't solve the problem globally, however, as it may become painful to change many .cs files to include this using statement.

Another alternative, may be to create a sub-class of the new type and name it the old name:

public class OldClassName : NewClassName

This gives you aliasing for the new class, but will require that you create duplicate public constructors and proxy static method calls to the renamed type. This is far from ideal ... and I generally don't recommend this.

0
Joshua On

Unfortunately, as the library author, the only way is X inherits Y, which has certain caveats.

It's possible but unlikely you could cheat with IL assembly.