0

I'm trying to convert objects dynamically based on a method's parameter object type using this line of code:

Convert.ChangeType(parameter.Value, parameterType);

However when parameterType is equivalent to DateTime? or int?, or any other nullable type, this conversion doesn't work.

Why does this conversion not work with nullable types, and is there a way to have it work with nullable types?

(Note: that this is all being done dynamically, so there is no way of knowing beforehand if the type will be nullable or not... unless the Type class has a way of deciphering that and I could then implement some type of if (nullable object) { // do special conversion }?)

EDIT:

Looking at this question: How to use Convert.ChangeType() when conversionType is a nullable int

I've tried implementing the following answer:

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);
} 

However this answer is used by doing something like:

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

But in my case I don't necessarily know it will be of type decimal?; I need to pass in the Type of which I want to convert it to, for example I need to do something like:

Type parameterType = parameterDescriptor.ParameterType;
var unknownType = GetValue<parameterType>(parameter.Value);
Community
  • 1
  • 1
keenns
  • 863
  • 4
  • 14
  • 26
  • 1
    Maybe a better duplicate: http://stackoverflow.com/questions/3531318 – D Stanley Dec 12 '16 at 20:25
  • Per edit: Then pass in the type as a second parameter instead of using generics. – Abion47 Dec 12 '16 at 20:52
  • @Abion47 But how would i then set the return-type object to be that of the type I passed in? – keenns Dec 12 '16 at 20:53
  • 1
    You can't. The only way you can have a volatile return type is with generics, which only works if the type is known at runtime. You'll have to set the return type as `object` so it can be anything. (If the number of possible types isn't too long, you can use a `switch` to do some post-processing on the object.) – Abion47 Dec 12 '16 at 21:01
  • 1
    Alternatively, you could see if you can set the return type of the method as `dynamic`. However, I would recommend against this, as using dynamic typing in C# is generally discouraged and is only really there for dealing with interop from dynamically-typed languages. – Abion47 Dec 12 '16 at 21:04
  • Thank you! That solved my problem :) – keenns Dec 12 '16 at 21:08

0 Answers0