I am aware this question may have been asked a thousand times but haven't managed to find the solution I seek on similar threads.
I have the following method which converts an object type to a generic type provided by the caller of the method.
public static T ConvertValue<T>(object value)
{
//conversion code
}
I am trying to use this method to convert the value type of an object's properties using Reflection.
Supposing we have the following object:
SomeClass someObject;
PropertyInfo myProperty = someObject.GetType().GetProperty("somePropertyName")
The following code works just fine:
string propertyValue = ConvertValue<string>(myProperty.GetValue(someObject));
However this forces me to write down the desired conversion type, while what I'd like to do is:
Type myPropertyType = prop.PropertyType;
var propertyValue = ConvertValue<myPropertyType>(myProperty.GetValue(someObject));
I understand usage is not intended by the compiler for various reasons, but I just can't come up with a simple solution for this..
Most solutions I found suggested passing the Type as a parameter and returning an object type.
public static object ConvertValue(object value, Type type)
{
//conversion code
}
But this seems to defeat the whole purpose as I must then make a cast of the output...