Mathias Brandewinder on .NET, F#, VSTO and Excel development, and quantitative analysis / machine learning.
by Mathias 22. November 2010 17:54

One of the reasons I like .NET extension methods is that they provide a nice way to work with existing libraries, and tweak the public API to create custom methods and extend existing objects without modifying them. For instance, I regularly end up creating a few when working with the Office interop. Imagine for instance that you had an Excel project where you wanted to apply a consistent format to some ranges; you could write an extension method like this one:

public static void ApplyStandardFormat(this Range range)
   range.Font.Bold = true;
   range.Font.Color = ColorTranslator.ToOle(System.Drawing.Color.White);

   range.Interior.Pattern = XlPattern.xlPatternSolid;
   range.Interior.Color = ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);

The nice thing here is that because of the addition of the this keyword in the signature “this Range range”, you can now use this method as if it was naturally exposed by the Range object, like this:


Arguable, this isn’t the greatest example, and doesn’t necessarily warrant an extension, but you get the idea.



Comment RSS