Summary: Using Extension Methods to make ESRI COM code more readable.
This post is the third post in my ArcObjects series.
Well after learning a bit about COM and interfacing lets talk about writing some nice clean code. Back in older times before C# 3.0 came around we really didn’t have much options – we could write wrapper classes around ArcObjects but the code in those wrappers usually wasn’t very maintainable. Moreover using Unit Tests to test most of those methods is quite impossible – instead it has become better to use Integration Unit Tests (test that access the DB).
But then came C# 3.0, when I first saw the feature of Extension Methods the first thing I asked “Does it work on interfaces?” when answered “Yes”, I knew what I wanted.
The easiest example would be getting a value from the IRow interface, using regular code it will look like this:
- public static object GetValue(IRow row, string field)
- {
- int fieldIndex = row.GetFieldIndex(field);
- if (fieldIndex == -1)
- throw new ArgumentException("Field " + field + " wasn't found in the table.");
- return row.get_Value(fieldIndex);
- }
Using it:
- object value = GetValue(row, field);
But using Extension Methods we can write a method such as:
- public static object GetValue(this IRow row, string field)
- {
- int fieldIndex = row.GetFieldIndex(field);
- if (fieldIndex == -1)
- throw new ArgumentException("Field " + field + " wasn't found in the table.");
- return row.get_Value(fieldIndex);
- }
And the using it will be as easy and readable as:
- object value = row.GetValue(field);
Now, it could be just me but I think using Extension Methods is more readable. Even more than that most developers like to write general methods but when using the first code sample you run into the risk of not finding the class containing the method. If developers can’t find the class/method these developers are likely going to “reinvent the wheel” and implement their own GetValue method.
You could view this method and even one better (that converts the object to a generic type) here, in my CodePlex project.
Resources:
Keywords: ESRI, ArcObjects, Extension Methods