Generic type casting
suggest change /// <summary>
/// Converts a data type to another data type.
/// </summary>
public static class Cast
{
/// <summary>
/// Converts input to Type of default value or given as typeparam T
/// </summary>
/// <typeparam name="T">typeparam is the type in which value will be returned, it could be any type eg. int, string, bool, decimal etc.</typeparam>
/// <param name="input">Input that needs to be converted to the specified type</param>
/// <param name="defaultValue">Returned when the value is null or conversion throws</param>
/// <returns>The input converted to T, or defaultValue</returns>
public static T To<T>(object input, T defaultValue)
{
var result = defaultValue;
try
{
if (input == null || input == DBNull.Value) return result;
if (typeof (T).IsEnum)
{
result = (T) Enum.Parse(typeof (T), input.ToString());
}
else
{
// ChangeType only performs conversions that IConvertible supports.
result = (T) Convert.ChangeType(input, typeof (T));
}
}
catch (Exception)
{
result = defaultValue;
}
return result;
}
/// <summary>
/// Converts input to Type of typeparam T
/// </summary>
/// <typeparam name="T">typeparam is the type in which value will be returned, it could be any type eg. int, string, bool, decimal etc.</typeparam>
/// <param name="input">Input that needs to be converted to the specified type</param>
/// <returns>The input converted to T, or default(T) when conversion fails</returns>
public static T To<T>(object input)
{
return To(input, default(T));
}
}
Usages:
std.Name = Cast.To<string>(drConnection["Name"]);
std.Age = Cast.To<int>(drConnection["Age"]);
std.IsPassed = Cast.To<bool>(drConnection["IsPassed"]);
// Casting type using default value
// Both of the following are correct
// Way 1 (In following style input is converted into type of default value)
std.Name = Cast.To(drConnection["Name"], "");
std.Marks = Cast.To(drConnection["Marks"], 0);
// Way 2
std.Name = Cast.To<string>(drConnection["Name"], "");
std.Marks = Cast.To<int>(drConnection["Marks"], 0);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents