Tuesday, November 21, 2006

Convert any possible type to T in .Net 2005

private T TryConvert <T>(object o, T defaultValue, bool isThrowException)
{
    T convertedValue = defaultValue;
    try
    {
     if (o != null)
      {
       convertedValue = (T)Convert.ChangeType(o, typeof(T));
      }
     else
      throw;
    }
    catch
    {
     if (isThrowException)
      {
       throw;
      }
    }
   return convertedValue;
}

How to use:


Let us suppose you have HttpRequest with some parameters:
ID , Name and Flag
Example 1. Simple using
private void Examle()
{
int id =
TryConvert<int>(Request["id"], -1,
true);
string name =
TryConvert<string>(Request["name"], string.Empty,
true);
bool flag =
TryConvert<bool>(Request["Flag"], default(bool),
true);
}


Example 2. Using in enum


 public enum Week
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

private void Examle2(Week w)
{
Week day = TryConvert<Week>(w, Week.Sunday, true);
}





1 comment:

Chris Pietschmann said...

A description of some usage senerios would be nice. When would you need to use this method?