RCode

a software development blog by Bojan Resnik

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.

kick it on DotNetKicks.comShout it

Advertisements

One Response to “Type Aliases in C#”

  1. Ecko said

    nice… thanks for your sharing..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: