I find the following scenario quite often: You have a string that you want to convert to an integer.
But first you must check:
string sId = null;
if (!string.IsNullOrEmpty(sId))
{
return int.Parse(sId);
}
else
{
return -1;
}
But what i want is to be able to do this:
sId.As<int>(-1)
So what i can do is write an exension method as follows:
public static class ObjectExtensions
{
public static T As<T>(this object instance, T defaultValue)
{
try
{
if (instance != null)
{
return (T)Convert.ChangeType(instance, typeof(T));
}
}
catch
{
}
return defaultValue;
}
}
My question is does anyone have a suggestion that this is a good approach?
Is there anything built into .NET 3.5 or up that is built in that can do this?