Top 5 Small but Must have Extension Methods

In this post I want to cover some very basic and small extension methods which are very useful for any developer. All below mentioned extension method are not doing any complex operation. Rather they are just performing very simple task which you generally encounter a lots of times in your day today coding.

1. IsNull

This is probably most commonly used expression. A lots of places in out code we check to null references. We usually add the obj == null or obj != null check to do this. Here is the IsNull extension method

public static bool IsNull(this object source)
{
    return source == null;
}

Using the you can avoid the lazy null check. Example:

public void ProcessData(DataSet input)
{
    if (!input.IsNull())
    {
        // business logic here
    }
}

2. FormatString

We often use string.Format to format the string like

string message = string.Format("Welcome {0} (Last login: {1})", 
    userName, lastLogin);

The alternative way to do this is using below extension method

public static string FormatString(this string format, params object[] args)
{
    return string.Format(format, args);
}

Now the above example can be re-written as

string message = "Welcome {0} (Last login: {1})".FormatString(userName, lastLogin);

3. RaiseEvent

How you generally raise you events? I guess something like below

protected void OnMyEvent(EventArgs e)
{
    if (MyEvent != null)
    {
        MyEvent(this, e);
    }
}

Here for each event you need to check the null reference before you raise it and also you create a new method so that you don’t have to add this check each place from where you are raising the event even if there is no special logic in the function. Here it the set of extension method to raise the events that matches the signature of EventHandler or EventHalder<TEventArgs>:

public static void Raise(this EventHandler eventHandler, 
    object sender, EventArgs e)
{
    if (eventHandler != null)
    {
        eventHandler(sender, e);
    }
}

public static void Raise<T>(this EventHandler<T> eventHandler,
    object sender, T e) where T : EventArgs
{
    if (eventHandler != null)
    {
        eventHandler(sender, e);
    }
}

Now this is how to raise the above event

MyEvent.Raise(this, e);

4. Match

This extension method is for pattern matching in any string using Regex. This is how you generally use it

Regex regex = new Regex("[0-9]");
if (regex.IsMatch(myData))
{
    // do someting
}

And here is the extension method to do this simply

public static bool Match(this string value, string pattern)
{
    Regex regex = new Regex(pattern);
    return regex.IsMatch(value);
}

After this look at the code below. It became much simpler than the traditional approach:

if (myData.Match("[0-9]"))
{
    // do someting
}

5. ToInt

This method has three flavors, for Int16, Int32 and Int64. This can be easily used while doing string to int conversion. Here are the methods:

public static long ToInt16(this string value)
{
    Int16 result = 0;

    if (!string.IsNullOrEmpty(value))
        Int16.TryParse(value, out result);

    return result;
}

public static long ToInt32(this string value)
{
    Int32 result = 0;

    if (!string.IsNullOrEmpty(value))
        Int32.TryParse(value, out result);

    return result;
}

public static long ToInt64(this string value)
{
    Int64 result = 0;

    if (!string.IsNullOrEmpty(value))
        Int64.TryParse(value, out result);

    return result;
}

I hope you enjoyed reading this article. You can download the source file from here also

Download Source Files

9 comment(S)


Sandor Drie&#235;nhuizen on May 31, 2009 03:06 AM

I think methods 1 and 2 don't add anything of value other than being an alternative. If they would add clearness, I'd agree but I think that's not the case. Second, method 4 would easily make you disregard the fact that creating a Regex instance is not free. The BCL designers did not leave out a static Regex.Match method by coincidence. Last, the ToInt methods seem incorrect to me because they well return 0 for anything that cannot be converted to an int. At least the method names should state this behavior. The RaiseEvent method (3) is quite nice though.

Sandor Drie&#235;nhuizen on May 31, 2009 03:09 AM

I have to recap what I said about Regex: there actually is a static Match method in the BCL:

Regex.Match(string input, string pattern);

Scott on Jun 2, 2009 07:27 AM

I must agree, creating Regex's are extremely expensive on the fly. We are talking about 1700 lines of code. Instead I would rather just create a a compiled Regex instead of compiling it on the fly.

RegexOptions.Compiled.... I Would never use your Regex method inside a loop...

Visual C# Kicks on Jun 2, 2009 08:24 PM

They look pretty good in terms of time saving. But as others have pointed out they are not optimal.

you are not too smart on Dec 17, 2009 09:02 AM

you are not too smart...

joakim on Apr 27, 2012 06:14 PM

Agree with the guy above here on your toInt() method. Here is what I use when I want a Int output:



/// <summary>
/// Takes the current strings value if it's an integer, else use a provided default
/// </summary>
public static int OrDefault(this string s, int defaultValue)
{
int result;

if (Int32.TryParse(s, out result)) { return result; }

return defaultValue;
}

And for string output:

/// <summary>
/// Takes the current strings value if it has a value else use a provided default
/// </summary>
public static string OrDefault(this string s, string defaultValue)
{
if (s.HasValue()) { return s; }

return defaultValue;
}

Usage:
var blah = foo.OrDefault(666);
var blah2 = foo2.OrDefault("default value");


joakim on Apr 27, 2012 06:17 PM

Sorry, My string output method is also depended on this method:

/// <summary>
/// More meaningful way to read if statements (if string.hasValue) rather than (if not string.IsNullOr*)
/// </summary>
/// <param name="checkWhiteSpace">Include whitespace check?</param>
/// <returns>Returns opposite of string.IsNullOr*()</returns>
public static bool HasValue(this string s, bool checkWhiteSpace = true)
{
return checkWhiteSpace ? !string.IsNullOrWhiteSpace(s) : !string.IsNullOrEmpty(s);
}

John on Oct 25, 2012 11:05 AM

I like what you have here... thought that i would add a couple more.
<code>
public static string RxReplace(this string str, string pattern, string value)
{
return Regex.Replace(str, pattern, value);
}
public static string RxRemove(this string str, string pattern)
{
return Regex.Replace(str, pattern, "");
}
</code>

Remy on Jan 9, 2013 03:14 AM

I think using extension methods for null-check on 'this' is a very bad idea as it breaks a pretty solid truth in .net. "Calling anything on a null reference will crash".
I like this rule. It is simple. Now with such EM, this simple truth now has an exception. I really wouldn't want to see that in the code of one of a project.

Leave a comment