Skip to content

Instantly share code, notes, and snippets.

@clemensv
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clemensv/639f832e5151482054f8 to your computer and use it in GitHub Desktop.
Save clemensv/639f832e5151482054f8 to your computer and use it in GitHub Desktop.
"alias" classes in C# ?!
Thought experiment:
Listened to eight .NET Rocks episodes yesterday while driving. One episode was about C# 6.0 with Bill Wagner
(http://www.dotnetrocks.com/default.aspx?showNum=1029), another about DDD with Steve Smith and Julie Lerman
(http://www.dotnetrocks.com/default.aspx?showNum=1023) where they specifically also discussed DDD's notion of
an anti-corruption layer, which aims to provide a neutral zone between different domains. The combination of
the two episodes gave me the following idea which I'll jot down here quickly.
Don't go "you dont do that in DDD, because .." since that's not the point. The point is efficiency and avoiding
data copies. Also, I'm not planning on doing anything further with it, so if anyone wants to take this somewhere,
have a ball...
--
Let there be a class in a namespace MyDomain
namepace MyDomain
{
public class Customer
{
public string FirstName;
public string LastName;
public DateTime DateOfBirth;
public string Zip;
public string State;
public string Street;
public string City;
public void Validate();
public int OtherMethod();
}
}
Now I want to use an instance of that class in a different context, but that context has a somewhat different notion of "Person". What we do today is making copies. What if we could just change the perspective? For simplicity, I'll make the perspective German.
namespace OtherDomain
{
public alias class Kunde : MyDomain.Customer
{
public string Vorname alias base.FirstName;
public string Nachname alias base.LastName;
public int Alter { get { return (DateTime.Now - base.DateOfBirth).TotalYears };
public string Postleitzahl alias base.Zip;
public string Stadt {get { return base.City + ", " + base.State }} ;
public void Pruefen()
{
///
base.Validate();
}
public alias OtherMethod();
}
..
Kunde k = new Customer(); //assignment compatible
Customer c = k; // INVALID. Not the same type
}
Rules:
* an alias class is a "smart pointer". it is a perspective on the object it aliases
* alias classes must not have local storage (no local fields or auto-properties)
* aliases cannot be independently instantiated they must be created by assigning an instance of the aliased class
* alias classes do not inherit any members by default. What is not explicitly aliased is not in scope.
* alias classes may implement get/set properties and methods.
* alias classes may be inherited from, but all the same rules apply to descendants
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment