简体   繁体   中英

Type aliases in C#

I'm looking for ways to add syntactic sugar to a project, and am considering adding an Alias class, that is a bit reminiscent of typedef in C++, with significant differences. The purposes of it are to provide a way to easily create shortened aliases for complex typenames, and to allow more flexibility with method overloading. It would look something like this:

The Class

public class Alias<T>
{
    private T Data { get; set; }

    public static implicit operator T(Alias<T> rhs)
    {
        return rhs.Data;
    }

    public static implicit operator Alias<T>(T rhs)
    {
        return new Alias<T> { Data = rhs };
    }

    // Dereferencing operator
    public static T operator ~(Alias<T> rhs)
    {
        return rhs.Data;
    }
}

Use Case 1: Shorten complex type names

// Declare alias somewhere for a cumbersome type, 
// like a dictionary of dictionaries
class UserFields : Alias<Dictionary<string, string>> {}
class UserInfos : Alias<Dictionary<int, UserFields>> {}

// Now use it
UserFields fields = new UserFields();
UserInfos infos = new UserInfos();
(~infos)[0] = fields;

Use Case 2: Method overloading

// Declare some aliases
class UserId : Alias<Int64> {}
class ProductId : Alias<Int64> {}

// Now we can distinguish between them, though they
// are both Int64's
public void DoSomething(UserId userId) { ... }
public void DoSomething(ProductId productId) { ... }


The examples are contrived, but hopefully illustrate my intentions. I'm afraid this might end up being hacky, with unexpected consequences. What are some of the pitfalls and problems with using the Alias class as described?

In terms of why it's a bad idea:

  • It isn't really an alias. Anywhere that doesn't let you use the implicit conversions won't work pleasantly with this.
  • You're using a class , which means you need to allocate an extra object every time you use this. It would be cleaner to use a struct
  • You're overloading the ~ operator for no particularly obvious reason - and certainly not in a way which is similar to the normal meaning of the operator in C#
  • You're using subclassing in a way which really isn't anything to do with specialization

You can consider using using directives as aliases:

using FooString = System.String;
...
FooString x = "whatever";

... with the disadvantage that the "alias" here is only applicable within the same source.

Personally if I wanted a mapping from string to string, I'd just use Dictionary<string, string> . Every C# developer wortht their salt would instantly know what it meant, there'd be nothing "odd" in terms of debugging, no extra allocations etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM