Skip to content

Instantly share code, notes, and snippets.

@NeilRobbins
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NeilRobbins/f0234a2fda079b50c9fe to your computer and use it in GitHub Desktop.
Save NeilRobbins/f0234a2fda079b50c9fe to your computer and use it in GitHub Desktop.
Aliasing in C#
public abstract class Alias
{
protected readonly string Value;
protected Alias(string value)
{
if (value == null) throw new ArgumentNullException("value");
if (string.Empty.Equals(value, StringComparison.InvariantCultureIgnoreCase))
throw new ArgumentException("Value must not be empty.", "value");
Value = value;
}
public static implicit operator string(Alias alias)
{
return alias.Value;
}
public override string ToString()
{
return Value;
}
}
public class Sql : Alias
{
public Sql(string sql) : base(sql)
{}
public static implicit operator Sql(string sql)
{
return new Sql(sql);
}
}

Why?

  1. In particular when using Func or similar types it can be hard to communicate the meaning. Creating an aliased type like this can provide a much stronger semantic.
  2. Similar to 1, in methods that return simple types, such as strings, it provides a stronger semantic to the signature if the type returned informs about the 'type' of string, rather than the simple fact of it being a string
  3. Similar, but when creating dictionary types, if the key is a string, what is special about it?
  4. Because I miss this capability in languages such as F# and Haskell (not that this is as good)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment