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

Very interesting
ReplyDelete