Extension Methods make life easier (C#)
I use extension methods when I remember they exist. I started getting tired of writing code to check strings for Null, Empty, Equal before using a database column when I remembered Extension Methods are there to make life easier! Some great articles/blog entries on it can be found at:
- Extending Base Type Functionality with Extension Methods – Scott Mitchell, 4 Guys From Rolla
- New "Orcas" Language Feature: Extension Methods – Scott Guthrie, PM, Microsoft ASP.NET Team
In a nutshell I found myself writing code that looks like:
1: if (!string.IsNullOrEmpty(details.FeedSourceTable) && details.FeedSourceTable.Equals("auto", StringComparison.CurrentCultureIgnoreCase))
2: {
3: }
After creating a (simple) string extension method I now have code that looks like:
1: if (details.FeedSourceTable.IsNotNullEmptyAndEquals("auto", StringComparison.CurrentCultureIgnoreCase))
2: {
3: }
To accomplish this I added a new class, ExtensionsString, to my root library (Sol3.dll) and added the extension methods to it. The class looks like:
1: using System;
2:
3: namespace Sol3
4: {
5: public static class ExtensionsString
6: {
7: public static bool IsNullOrEmpty(this string source)
8: {
9: return string.IsNullOrEmpty(source);
10: }
11: public static bool IsNotNullEmptyAndEquals(this string source, string target)
12: {
13: if (!string.IsNullOrEmpty(source) && source.Equals(target))
14: return true;
15: else
16: return false;
17: }
18: public static bool IsNotNullEmptyAndEquals(this string source, string target, StringComparison compareOption)
19: {
20: if (!string.IsNullOrEmpty(source) && source.Equals(target, compareOption))
21: return true;
22: else
23: return false;
24: }
25: }
26: }
The key parts to understand while writing Extension Methods:
- The class has to be static (in VB it would be a Module instead)
- The Class name should not be a duplicate of another class name (hopefully this is obvious)
- The first parameter must include the keyword this followed by the data type to extend. (Line 7, 11 and 18 illustrate this)
I won’t go into to much more detail as the 2 links I gave at the beginning of this blog entry have more than enough info. Scott Mitchell’s article also has a VB example.