I currently use this handy conversion extension method to do conversions between types:
public static T To<T>(this IConvertible obj) { return (T)Convert.ChangeType(obj, typeof(T)); }
However, it doesn't like converting valid values to Nullable, for example, this fails:
"1".To<int?>();
Obviously, 1 is easily converted to an (int?), but it gets the error:
Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
This is an obviously simplified example, in reality I'm using it to do conversions from string types like so:
packageDb.Quantity = package.package.ElementDeep(Namespace + "PackageQuantity", Namespace + "ActualQuantity", Namespace + "Quantity").ValueOrNull().To<int?>();
If Convert.ChangeType doesn't like Nullable, anyone have any great ideas?
This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. Also, we cannot simply return null from a generic method like in normal method.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
To make Value Types nullable, we create a wrapper around existing value type by appending a question mark ? next to it. This way a Value Type becomes nullable in C#.
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values. For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable.
public static T To<T>(this IConvertible obj) { Type t = typeof(T); Type u = Nullable.GetUnderlyingType(t); if (u != null) { return (obj == null) ? default(T) : (T)Convert.ChangeType(obj, u); } else { return (T)Convert.ChangeType(obj, t); } }
public static T To<T>(this IConvertible obj) { Type t = typeof(T); if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) t = t.GetGenericArguments()[0]; return (T)Convert.ChangeType(obj, t); }
But if the conversion fail, it will throw an exception, not returning a null as should be expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With