Type Aliases in C#
Posted by Bojan Resnik on August 14, 2009
I was maintaining a piece of C# code today, which made heavy use of a class with several generic parameters. The class has several static methods and nested types, so its full signature was all over the place:
private Graph<int, object, List<int>> CreateGraph() { var result = new Graph<int, object, List<int>>(); // Code to populate the graph... return result; } private void Traverse(Graph<int, object, List<int>> graph) { foreach (var node in graph.Roots) Traverse(node); } private void Traverse(Graph<int,object,List<int>>.Node node) { // Do something with node... foreach (var child in node.Children) Traverse(child); }
This is just a sample of the code – almost every method in the class had Graph<int, object, List<int>>
somewhere in it. The code would be much easier to maintain if it didn’t depend on this full signature so heavily. Fortunately, C# provides a convenient way to solve this with type aliases:
using DocumentGraph = Graph<int, object, List<int>>;
The offending code can now use DocumentGraph
:
private DocumentGraph CreateGraph() { var result = new DocumentGraph(); // Code to populate the graph... return result; } private void Traverse(DocumentGraph graph) { foreach (var node in graph.Roots) Traverse(node); } private void Traverse(DocumentGraph.Node node) { // Do something with node... foreach (var child in node.Children) Traverse(child); }
The type alias directive can be specified at file or namespace scope – it cannot be specified in a class or method.
Ecko said
nice… thanks for your sharing..