Reputation: 870
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?
Upvotes: 0
Views: 1294
Reputation: 269498
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();
Upvotes: 3
Reputation: 48623
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 { ... }
Upvotes: 2
Reputation: 27727
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();
Upvotes: 2