0

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...

Innat3
  • 3,561
  • 2
  • 11
  • 29
  • You're still specifying the type by declaring `property_value` as `string`. It's not clear how you expect this to work - what is the relationship between `myPropertyType` and `string` in this case? – Lee May 22 '17 at 10:52
  • 3
    You can´t expect your compiler to infer a type you provide at runtime. Thus you *allways* have to do the cast to that actual type as otherwise your method just returns an `object`. – MakePeaceGreatAgain May 22 '17 at 10:54
  • @Lee oops sorry I meant to assign the **var** type instead of string – Innat3 May 22 '17 at 11:26

0 Answers0