Generic type casting C# with Example
/// /// Converts a data type to another data type. /// public static class Cast { /// /// Converts input to Type of default value or given as typeparam T /// /// typeparam is the type in which value will be returned, it could be any type eg. int, string, bool, decimal etc. /// Input that need to be converted to specified type /// defaultValue will be returned in case of value is null or any exception occures /// Input is converted in Type of default value or given as typeparam T and returned public static T To(object input, T defaultValue) { var result = defaultValue; try { if (input == null || input == DBNull.Value) return result; if (typeof (T).IsEnum) { result = (T) Enum.ToObject(typeof (T), To(input, Convert.ToInt32(defaultValue))); } else { result = (T) Convert.ChangeType(input, typeof (T)); } } catch (Exception ex) { Tracer.Current.LogException(ex); } return result; } /// /// Converts input to Type of typeparam T /// /// typeparam is the type in which value will be returned, it could be any type eg. int, string, bool, decimal etc. /// Input that need to be converted to specified type /// Input is converted in Type of default value or given as typeparam T and returned public static T To(object input) { return To(input, default(T)); } } Usages: std.Name = Cast.To(drConnection["Name"]); std.Age = Cast.To(drConnection["Age"]); std.IsPassed = Cast.To(drConnection["IsPassed"]); // Casting type using default value //Following both ways 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(drConnection["Name"], ""); std.Marks = Cast.To(drConnection["Marks"], 0);