How to use Convert.ChangeType () when conversionType is a value with int value of zero

I mean, I want to convert this:

string a = 24; Convert.ChangeType(a, typeof(decimal?)) 

But that gives me an error.

UPDATE 1:

I have an object of type that can be decimal ?, int?, .. many types with null value. Then, with the Type object, I need to convert the string value to a type object.

+4
source share
3 answers

You cannot do this because Nullable<T> does not implement IConvertable .

You can do it though.

 string a = 24; decimal? aAsDecimal = (decimal)Convert.ChangeType(a, typeof(decimal)); 

May I also interest you in TryParse ?

+1
source

See a great answer here :

 public static T GetValue<T>(string value) { Type t = typeof(T); t = Nullable.GetUnderlyingType(t) ?? t; return (value == null || DBNull.Value.Equals(value)) ? default(T) : (T)Convert.ChangeType(value, t); } 

eg:.

 string a = 24; decimal? d = GetValue<decimal?>(a); 
+19
source

This is based on Dror's answer, but has slightly less overhead when dealing with null values:

 public static T GetValue<T>(string value) { if(value == null || DBNull.Value.Equals(value)) return default(T); var t = typeof(T); return (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(t) ?? t); } 
+4
source

All Articles