Permalink
Browse files

2012-Jan-18, DoctorRob - added function to type nullable fields.

  • Loading branch information...
1 parent 4eaf506 commit 4c6dc1ef54c09491b195443731c5ece7f19a0d53 @DoctorRob DoctorRob committed Jan 19, 2012
Showing with 33 additions and 1 deletion.
  1. +33 −1 RhoconnectNET/RhoconnectNET/Lib/Helpers.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections;
+using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using System.Reflection;
@@ -46,9 +47,40 @@ public static void merge_changes(Object obj, Dictionary<string, object> changes)
// skip unknown properties
if (property == null)
continue;
- Object convValue = Convert.ChangeType(kvp.Value, property.PropertyType);
+ Object convValue = ChangeType(kvp.Value, property.PropertyType);
property.SetValue(obj, convValue, null);
}
}
+
+ public static object ChangeType(object value, Type conversionType)
+ {
+ // Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
+ // checking properties on conversionType below.
+ if (conversionType == null)
+ {
+ throw new ArgumentNullException("conversionType");
+ } // end if
+
+ // If it's not a nullable type, just pass through the parameters to Convert.ChangeType
+
+ if (conversionType.IsGenericType &&
+ conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
+ {
+ // It's a nullable type, so determine what the underlying type is
+ if (value == null)
+ {
+ return null;
+ }
+
+ // It's a nullable type, and not null, so that means it can be converted to its underlying type,
+ // so overwrite the passed-in conversion type with this underlying type
+ NullableConverter nullableConverter = new NullableConverter(conversionType);
+ conversionType = nullableConverter.UnderlyingType;
+ } // end if
+
+ // Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
+ // nullable type), pass the call on to Convert.ChangeType
+ return Convert.ChangeType(value, conversionType);
+ }
}
}

0 comments on commit 4c6dc1e

Please sign in to comment.