Wednesday, December 9, 2009

Using C# extension methods for Revit Element Parameters

One of the places using C# extension methods shines is writing getters and setters for element parameters in Autodesk Revit Architecture 2010. Parameters are user defined meta data bound to either an instance or a type in Revit. Accessing these is a bit cumbersome:

public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
    var document = commandData.Application.ActiveDocument;    
    
    Parameter parameter = document.ProjectInformation.get_Parameter("BuildingCategory");
    if (parameter != null)
    {                
        var buildingCategory = parameter.AsInteger();
        // do something with this information
    }        
}

Imagine typing all that code every time you want to access your parameter in code! Of course you will wrap it up in a method, but wrapping it in an extension method allows for neat syntax:

public static int GetBuildingCategory(this ProjectInfo self)
{
        
    Parameter parameter = self.get_Parameter("BuildingCategory");
    if (parameter != null)
    {
                
        return parameter.AsInteger();
    }        
    // you could also throw an exception here...
    return 0;
}


Now, you can access the property through the element itself, and it shows up in intellisense!

int buildingCategory = document.ProjectInformation.GetBuildingCategory();

In fact, I go a step further in my project, utilizing the t4 templating engine to generate the parameter accessors as well as routines to bind them to the document from an XML file. But that will have to wait for another blog post.

No comments:

Post a Comment