How to alias a built-in type in C#?

Viewed 12445

So in C++, I'm used to being able to do:

typedef int PeerId;

This allows me to make a type more self-documenting, but additionally also allows me to make PeerId represent a different type at any time without changing all of the code. I could even turn PeerId into a class if I wanted. This kind of extensibility is what I want to have in C#, however I am having trouble figuring out how to create an alias for 'int' in C#.

I think I can use the using statement, but it only has scope in the current file I believe, so that won't work (The alias needs to be accessible between multiple files without being redefined). I also can't derive a class from built-in types (but normally this is what I would do to alias ref-types, such as List or Dictionary). I'm not sure what I can do. Any ideas?

6 Answers

I also sometimes feel I need (integer) typedefs for similar purposes to the OP.

If you do not mind the casts being explicit (I actually want them to be) you can do this:

enum PeerId : int {};

Will also work for byte, sbyte, short, ushort, uint, long, or ulong (obviously).

Not exactly the intended usage of enum, but it does work.

Since C# 10 you can use global using:

global using PeerId = System.Int32;

It works for all files.

It should appear before all using directives without the global modifier.

See using directive.

Related