A few extension methods that I have loved
Ever since extension methods were introduced into C# (and I don’t exactly remember when that was because my memory totally sucks) I have found uses for them. In my opinion, the initial fears surrounding extension methods have proved false. I do not feel they make code difficult or hard to follow. They have allowed me organize my “utility” classes and write some very expressive code (in most cases). Also, extension methods allow you to do some convenient things because you can call them on null references (under the covers its a static method after all).
String Extensions
Here are a few string extension methods that I use. The one I will probably get flack for is the F method. The name is not very expressive but it is very compact, which is what I was going for. I really dislike using string.Format and this provides a compact alternative. Any suggestions for another name would be welcome, though.
string result = “Hello, {0}!”.F(userName);
Note, I express the positive “HasValue” as well as the negative “IsNullOrEmpty”. I think most people know that it’s good to be consistent with the code you write. However, I have both of these methods because I have found that context matters. If I am writing a guard clause for instance, I might use IsNullOrEmpty. If I am writing “bidness rulez” I might use HasValue….well, maybe.
public static class StringExtensions
{
public static string F(this string format, params object[] args)
{
return format == null ? string.Empty : string.Format(format, args);
}
public static bool IsNullOrEmpty(this string input)
{
return (input == null) || input.All(char.IsWhiteSpace);
}
public static bool HasValue(this string input)
{
return !input.IsNullOrEmpty();
}
}
Enumerable and Enumerable<T> Extensions
When all you have is an IEnumerable or an IEnumerable
public static class EnumerableExtensions
{
public static int Count(this IEnumerable input)
{
int count = 0;
var enumerator = input.GetEnumerator();
while(enumerator.MoveNext())
{
count++;
}
return count;
}
public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
{
if (list == null)
return;
foreach(var item in list)
{
action(item);
}
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list)
{
return (list == null || list.Count() == 0);
}
}
IList Extension Methods
Similar to my IEnumerable extension methods, here are a few I have found convenient to have for IList. The Remove method which takes a Predicate
public static class ListExtensions
{
public static void AddRange<T>(this IList<T> list, IEnumerable<T> values)
{
foreach (T value in values)
{
list.Add(value);
}
}
public static void Remove<T>(this IList<T> list, Predicate<T> predicate)
{
if (list.Count == 0)
return;
var deletes = list.Where(value => predicate(value)).ToList();
foreach (var delete in deletes)
{
list.Remove(delete);
}
}
public static bool IsNullOrEmpty<T>(this IList<T> list)
{
return (list == null || list.Count() == 0);
}
public static bool HasValues<T>(this IList<T> list)
{
return !IsNullOrEmpty(list);
}
}
Some Admittedly Dangerous Extension Methods
I will openly admit that extension methods like the following can be dangerous. I consider these “white box” extension methods, because you need to know some things before you can call them. These fall into the category of pure convenience for me.
Object Extension Methods
public static class ObjectExtensions
{
// for type casting
public static T As<T>(this object obj) where T:class
{
return obj as T;
}
}
byte[] Extension Methods
public static class ByteArrayExtensions
{
public static T Deserialize<T>(this byte[] bytes)
{
var formatter = new BinaryFormatter();
var stream = new MemoryStream(bytes);
return (T)formatter.Deserialize(stream);
}
}
Additional String Extensions
public static class StringExtensions
{
// Deserialize XML
public static T FromXml<T>(this string input) where T:class
{
var xs = new XmlSerializer(typeof(T));
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(input));
var xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
var result = xs.Deserialize(memoryStream) as T;
return result;
}
}
Conclusion
OK, the end. I have shown you a few extension methods that I have found particularly useful. I know many of you are chomping at the bit to offer me your opinions and what not. No shortage of those out there. So, have a good day. Hope you got a few ideas.