Convert to a Type on the fly in C#.NET
You need to use the Convert.ChangeType(...) function [note: in the function below, the input propertyValue could just as easily have been of type object ... I just had a string version pre-baked]:
/// <summary>
/// Sets a value in an object, used to hide all the logic that goes into
/// handling this sort of thing, so that is works elegantly in a single line.
/// </summary>
/// <param name="target"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void SetPropertyValueFromString(this object target,
string propertyName, string propertyValue)
{
PropertyInfo oProp = target.GetType().GetProperty(propertyName);
Type tProp = oProp.PropertyType;
//Nullable properties have to be treated differently, since we
// use their underlying property to set the value in the object
if (tProp.IsGenericType
&& tProp.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
//if it's null, just set the value from the reserved word null, and return
if (propertyValue == null)
{
oProp.SetValue(target, null, null);
return;
}
//Get the underlying type property instead of the nullable generic
tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
}
//use the converter to get the correct value
oProp.SetValue(target, Convert.ChangeType(propertyValue, tProp), null);
}
A universal Type Converter is what you seek !? Not an easy feat..
Try this approach:
Universal Type Converter
You can in NuGet Install-Package UniversalTypeConverter
Also, is using Generics
out of the question here? It would facilitate the solution if you know at least the target type of the conversion.
Here's another way you can do it, but I'm not sure
Without support for generic types:
public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type type = obj.GetType().GetProperty(propertyName).PropertyType;
obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
}
With support for generic types:
public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type type = obj.GetType().GetProperty(propertyName).PropertyType;
if (type.IsGenericType)
type = type.GetGenericArguments()[0];
obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
}