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:
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;
}
}
// 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;
// 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) { ... }
Alias
class as described?
In terms of why it's a bad idea:
class
, which means you need to allocate an extra object every time you use this. It would be cleaner to use a struct
~
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 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.
See more on this question at Stackoverflow