/// <summary> /// Maps a field name value pair to the matching property on the target object /// </summary> /// <param name="targetObj">The object to assign a parameter value to</param> /// <param name="fieldName">The name of the parameter</param> /// <param name="fieldValue">The value to be assigned</param> public static void GenericMapField(object targetObj, string fieldName, object fieldValue) { PropertyInfo prop = targetObj.GetType().GetProperty(fieldName); if (prop != null) { if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { dynamic objValue = System.Activator.CreateInstance(prop.PropertyType); objValue = fieldValue; prop.SetValue(targetObj, (object)objValue, null); } else { prop.SetValue(targetObj, fieldValue, null); } } }
A technical blog from an ASP.NET / C# developer about anything I find interesting or useful.
Friday, 4 November 2011
Using reflection to map values to properties that could be nullable in C# 4
I encountered an issue with a piece of reflection code that someone had written before I joined the project. They were mapping to fields on a class that matched the column names on a database. The only problem was that when the field was a nullable datetime any combination of Convert and SetValue I tried resulted in an error due to the absence of a Convert function for DateTime. The solution I came up with was to use the dynamic keyword to declare an initialised Nullable generic so that assignment of null to the object acted exactly as if it was being assigned to an actual Nullable object.
Subscribe to:
Posts (Atom)