Search code examples
c#visual-studioreflectioncasting

C# - Dynamic casting using reflection


I am trying to pull values from a datatable object and populate an object for a webservice call dynamically, I have tried a few aproaches but narrowed them down to this, what it seems to be missing is the ability to reflect the target type and cast the object from the data table into one.

I'm scratching my head a lot here!

foreach (PropertyInfo pi in zAccount)
                {
                    object o = row[pi.Name];
                    if (o.GetType() != typeof(DBNull))
                    {
                        pi.SetValue(a, o, null);
                    }
                 }

This gives me type conversion errors:

Object of type 'System.String' cannot be converted to type 'System.Nullable`1[System.Boolean]'.

So the ideal would be something like this:

foreach (PropertyInfo pi in zAccount)
                {
                    object o = typeof(pi.GetType())row[pi.Name];
                    pi.SetValue(a, o, null);
                 }

Solution

  • Here is a piece of code that I use to do exactly what you are trying to do; convert types out of the DB. Normally you could use Convert.ChangeType, but that doesn't work right with nullable types, so this method handles that case.

    /// <summary>
    /// This wrapper around Convert.ChangeType was done to handle nullable types.
    /// See original authors work here: http://aspalliance.com/852
    /// </summary>
    /// <param name="value">The value to convert.</param>
    /// <param name="conversionType">The type to convert to.</param>
    /// <returns></returns>
    public static object ChangeType(object value, Type conversionType)
    {
      if (conversionType == null)
      {
        throw new ArgumentNullException("conversionType");
      }
      if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
      {
        if (value == null)
        {
          return null;
        }
        NullableConverter nullableConverter = new NullableConverter(conversionType);
        conversionType = nullableConverter.UnderlyingType;
      }
      return Convert.ChangeType(value, conversionType);
    }
    

    You would then use it like:

    foreach (PropertyInfo pi in zAccount)
    {
      object o = ChangeType(row[pi.Name], pi.GetType());
      pi.SetValue(a, o, null);
    }
    

    Edit:

    Actually, re-reading your post, your error message

    Object of type 'System.String' cannot be converted to type 'System.Nullable`1[System.Boolean]'.

    makes it look like the type that you got back from the database is a string, but the property is of type bool? (nullable boolean) hence it can't convert it.