Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Convert.ChangeType() when conversionType is a nullable int

Tags:

c#

I mean, I want to convert this:

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

But it throws me an error.

UPDATE 1:

I've got a Type object where can be decimal?, int?, .. many nullable types. Then with the Type object, I need to convert the string value in type object.

like image 850
Darf Avatar asked Sep 05 '11 23:09

Darf


1 Answers

See an excellent 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);
} 

E.g.:

string a = 24;
decimal? d = GetValue<decimal?>(a);
like image 123
Dror Avatar answered Oct 13 '22 00:10

Dror