8

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.

Darf
  • 2,495
  • 5
  • 26
  • 37

3 Answers3

24

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);
Community
  • 1
  • 1
Dror
  • 1,406
  • 12
  • 15
5

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);
} 
Ziad
  • 1,036
  • 2
  • 21
  • 31
  • I also added a check for null or whitespace but this is a great answer thank you string.IsNullOrWhiteSpace(value.ToString()) – workabyte Nov 04 '14 at 15:43
3

You can't do this since Nullable<T> don't implement IConvertable.

You can do this although.

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

Might I also interest you in TryParse?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445