.Net 3.5 Extension Methods

Since the “dawn” of .Net 2.0 and 3.5 a while ago, life in programming has become significantly easier. The new language features have helped me in my philosophy of creating cleaner code.

An example of this has been using extension methods. In the old days you used to have a Utility library which had generic functions to help abstract various operations.

Once such operation (and which is widely used) is casting a string value (from some source) to a specified type (like int or double etc).

Old Way:

public class Utils {
public static int SafeInt(string val)
{
try
{
return (int)val;
}
catch (Exception ex)
{
//log error to error handler
ErrorGateway.LogError(ex.Message, ex);
//possible rethrow of exception
}
return 0;
}
}


You would have had to write one method for each type you want to cast. You would call this function using something like:

string cast = “123”;
int ret= Utilities.Utils.SafeInt(cast);


With the new .Net 3.5 you can rewrite it using the following method:

public static T SafeType(this object val)
{
try
{
var tempValue = Convert.ChangeType(val, typeof(T));
var value = (T)tempValue;
return value;

}
catch (Exception ex)
{
ErrorGateway.LogError(ex.Message, ex);
}
return default(T);
}

This is a form of an extension method in .Net 3.5. This provides numerous advantages:

  • Allows re-use of this method with any type. This of course leads to cleaner code.
  • Provides an additional method to a sealed type which makes calling easier.

Example usage:

string cast = “123”;
int ret = cast.SafeType();



This is just one example of how useful these new features can be as this reduces code and ease of use.

Hope this has been helpful.

–Lee

Advertisements

One Response to “.Net 3.5 Extension Methods”

  1. Ntsika Says:

    Very interesting

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: