How can I make this function reliably cast sourceValue to type T where sourceValue is bool and T is int?
public static T ConvertTo<T>(Object sourceValue) { // IF IS OF THE SAME TYPE --> RETURN IMMEDIATELY if (sourceValue is T) return (T) sourceValue; var val = ConvertTo(sourceValue, typeof (T)); return (T) val; }
Currently, this throws an InvalidCastException when trying to convert false to 0 and true to 1. The types are not predefined, which is why generics must be used here. However, the only case where it fails is when T:Int32 and sourceValue:Boolean.