views:

60

answers:

3

I've got a problem converting an object property to string while using reflection...

string value = Convert.ToString(typeof(T).GetProperty(ValueField).GetValue(data, null));

This throws 'Object does not match target type.' when returning any type other than string?

+2  A: 

If for some reason you don't want to use the property's ToString method, you can constrain T to classes that implement IConvertible:

public string DoSomething<T>(object data) where T: IConvertible { ... }
Jeff Sternal
While the other two solutions are more pragmatical, I give you +1 as well for solving the problem in another way.
OregonGhost
I'm a bit embarrassed that this was due to question-induced-tunnel-vision for my initial answer, so many thanks :) (Plus, it's possible that someone might override ToString and IConvertible.ToString in different ways.)
Jeff Sternal
As awesome as your answer is. I have to note that i was pointing the GetValue to the collection instead of the correct object... :)
Jan de Jager
+2  A: 

You can't cast every object to a string, but every object has a ToString method. So you can change your code to:

string value = typeof(T).GetProperty(ValueField).GetValue(data, null).ToString();
Jake Pearson
+3  A: 

Use the type's built-in ToString method instead of calling Convert.ToString. All types have a ToString method inherited from object, whereas Convert.ToString only works for types that implement the IConvertible interface.

string value =
    typeof(T).GetProperty(ValueField).GetValue(data, null).ToString();
LukeH