Bugs, Workarounds, And Gotchas in VS 2008: Keeping Your Extension Methods Under Control

Extension methods have the capacity for misuse, but a few simple guidelines will let you leverage their power:

  1. Extension methods should handle null/Nothing for the first (extension) parameter in an appropriate way. It should only throw an exception if you want it to behave exactly like an instance method.
  2. When working with a tree, put the method on the class closest to the leaf. For example, instead of "GetStringAttribute" on XElement, create GetString that works directly with the XAttribute and returns an empty string or null if the attribute is null.
  3. Categorize extension methods as either organizational or project. Separate organizational and project extension methods into different assemblies. This will make it easier to reference correct extension methods for a given project. Be small grained on these assemblies.
  4. Keep extension methods in the same namespaces whether they are project or organizational. Either one namespace or namespaces that track the category of extension methods such as StringExtensions. This makes it easier to move extension methods from projects into organizational assemblies.
  5. Keep project extension methods with the same name in sync. The same name should not be used differently in different projects.
  6. Extension methods should have good names. Standard guidelines are Pascal cased, no underscores, each word starting with a capital, no abbreviations. Because they are methods, they should include a verb.
  7. Provide overloads if some parameters can be set to a default. Set a single order of parameters and pick the most logical overloads. Don't provide too many overloads.
  8. When providing a variation of existing framework functionality, use an overload of the same name or starting with the same characters. If you're creating parallel functionality (such as providing List behavior to System.Collections.ObjectModel.Collection) use the same signatures.
  9. Expect some work when you move to future .NET versions. This will occur if your signatures conflict. If you've worked logically and followed these guidelines, changes should be minimal.
comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.