Hi HairlipDog,
Thanks for your post.
public static object Convert.ChangeType(object, TypeCode); method has the
similiar function, It can change an object instance into a type which
TypeCode equals to TypeCode parameter.
However, for your specific request, it seems that .Net Framework did not
have build-in method. We can build a method of this function ourselves.
If we use Reflector to view Convert.ChangeType's source code, we will see
that it internally uses switch case statement to do the conversion. Listed
below:
public static object ChangeType(object value, TypeCode typeCode,
IFormatProvider provider)
{
IConvertible convertible1 = value as IConvertible;
if (convertible1 == null)
{
if ((value != null) || (typeCode != TypeCode.Empty))
{
throw new
InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible
"));
}
return null;
}
switch (typeCode)
{
case TypeCode.Empty:
{
throw new
InvalidCastException(Environment.GetResourceString("InvalidCast_Empty"));
}
case TypeCode.Object:
{
return value;
}
case TypeCode.DBNull:
{
throw new
InvalidCastException(Environment.GetResourceString("InvalidCast_DBNull"));
}
case TypeCode.Boolean:
{
return convertible1.ToBoolean(provider);
}
case TypeCode.Char:
{
return convertible1.ToChar(provider);
}
case TypeCode.SByte:
{
return convertible1.ToSByte(provider);
}
case TypeCode.Byte:
{
return convertible1.ToByte(provider);
}
case TypeCode.Int16:
{
return convertible1.ToInt16(provider);
}
case TypeCode.UInt16:
{
return convertible1.ToUInt16(provider);
}
case TypeCode.Int32:
{
return convertible1.ToInt32(provider);
}
case TypeCode.UInt32:
{
return convertible1.ToUInt32(provider);
}
case TypeCode.Int64:
{
return convertible1.ToInt64(provider);
}
case TypeCode.UInt64:
{
return convertible1.ToUInt64(provider);
}
case TypeCode.Single:
{
return convertible1.ToSingle(provider);
}
case TypeCode.Double:
{
return convertible1.ToDouble(provider);
}
case TypeCode.Decimal:
{
return convertible1.ToDecimal(provider);
}
case TypeCode.DateTime:
{
return convertible1.ToDateTime(provider);
}
case TypeCode.String:
{
return convertible1.ToString(provider);
}
}
throw new
ArgumentException(Environment.GetResourceString("Arg_UnknownTypeCode"));
}
So we can also write a large switch case statement to return corresponding
Type based on the TypeCode.
Hope this helps.
Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! -
www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.