Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to create "aliases" for classes

Tags:

c#

alias

I don't even know if it's called an alias, but let me continue anyway.

You know how the System.String type in C# is sorta "aliased" with "string"? In Visual Studio, "string" is in lowercase and blue text. I'd like to do this to some of our lengthy class names. Some are all like "RelocatedPlantProductReleaseItem". I can't change the name of it, but such a long name really makes the code long-winded. I'd like to be able to use "Rppr" instead. So instead of this:

RelocatedPlantProductReleaseItem Item = new RelocatedPlantProductReleaseItem();

I'd go like:

Rppr Item = new Rppr();

I know that I can create a class called Rppr and have it inherit from RelocatedPlantProductReleaseItem, but that seems hacky.

Also, the scenario I gave above is totally fictitious. I just used it to demonstrate the essential functionality I am trying to achieve.

Also, what is it technically called when "string" represents System.String?

I want this to be a global thing. I don't want to have to specify it at the top of every code file. I want to specify it in one place and it work everywhere in the entire application, even in other assemblies that reference its assembly.

like image 575
oscilatingcretin Avatar asked Aug 16 '11 17:08

oscilatingcretin


3 Answers

Use a using directive

using Rppr = Namespace.To.RelocatedPlantProductReleaseItem;

EDIT Op clarified to ask for a global solution.

There is no typedef style equivalent in C# which can create a global replacement of a type name. You'll need to use a using directive in every file you want to have this abbreviation or go for the long version of the name.

like image 92
JaredPar Avatar answered Nov 12 '22 14:11

JaredPar


string is a convenience offered by the C# language to refer to the actual CLR type System.String.

You can achieve similar results with a using directive. At the top of the file where you'd like the name shortened, add this line:

using ShortName = Namespace.ReallyLongClassNameGoesHereOhGodWhy;

Then you can say ShortName myVar = new ShortName();

Note that you have to do this on a per file basis. You can't get the same coverage as string with a single declaration.

like image 34
dlev Avatar answered Nov 12 '22 13:11

dlev


Try

using Rppr = SomeNamespace.RelocatedPlantProductReleaseItem;

Reference

like image 4
Bala R Avatar answered Nov 12 '22 14:11

Bala R