One Use for Extension Methods

By Michael Flanakin @ 5:44 PM :: 1706 Views :: .NET, Development :: Digg it!

Microsoft .NET

I like extension methods. Some people suggest you avoid the feature, which I believe is understandable, but the more I think about it, the more I want to use it. Don't get me wrong, I'm not using them all over the place, but when they make sense, it can make your code much cleaner.

As you may know, I'm working on custom code analysis rules to enforce coding standards. To make the rules testable, I decided to front the code analysis types with my own object model. To do this, I created a factory to create my types -- CodeItemFactory.Create(Member). While creating a new rule, I wanted to see if the current member had a sibling member with a specified name and then return that. At first, I started to add a new method to the CodeItem class, but then I realized I'd have to reference the CodeItemFactory class. While I'm in the same assembly, I didn't like the idea of putting this logic into the domain object and creating a circular dependency. Plus, since the code analysis framework isn't "officially supported," there are no promises on what will be available in the future. Keeping my integration code separate is just a good idea. So, I ultimately decided to create an extension method to do what I needed -- CodeItemExtension.GetSibling(this CodeItem, string). This enabled me to have a clean code implementation and keep my purist ideals of separating integration code -- codeItem.GetSibling(memberName).

There are plenty other reasons to love extension methods, but I just wanted to share this because I feel like it's a very nice solution that keeps life simple.