Jan de Jager
Jan de Jager

Reputation: 870

Converting Reflected Property to String

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

Answers (3)

LukeH
LukeH

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

Jeff Sternal
Jeff Sternal

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

Jake Pearson
Jake Pearson

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

Related Questions