void.pointer void.pointer - 6 months ago 49
C# Question

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

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?


You could (ab)use implicit conversions:

struct PeerId
    private int peer;

    public static implicit operator PeerId(int i)
        return new PeerId {peer=i};

    public static implicit operator int(PeerId p)
        return p.peer;

This takes the same space as an int, and you can do:

PeerId p = 3;
int i = p;

But I agree you probably don't need this.