70

I want to convert a string to a generic type

I have this:

string inputValue = myTxtBox.Text; PropertyInfo propInfo = typeof(MyClass).GetProperty(myPropertyName); Type propType = propInfo.PropertyType; object propValue = ????? 

I want to convert 'inputString' to the type of that property, to check if it's compatible how can I do that?

tks

4 Answers 4

128
using System.ComponentModel; TypeConverter typeConverter = TypeDescriptor.GetConverter(propType); object propValue = typeConverter.ConvertFromString(inputValue); 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm surprised that this one gets the upvotes compared to Convert.ChangeType.
Probably because ChangeType tries to cast, not convert. For example, ChangeType can't go from String to Nullable<Int64> - TypeConverter can.
Nor can it handle automatic parsing of enums
Convert.ChangeType also fails for string -> Guid
16

Try Convert.ChangeType

object propvalue = Convert.ChangeType(inputValue, propType); 

5 Comments

This is really a comment, not an answer to the question. Please use "add comment" to leave feedback for the author.
@SteveGuidi: Default already edited the answer in the meantime, tnx to both.
@SWeko it's the default reply when editing via the review page (and this question was there for both of us). I just edited it instead.
This is really the the proper way to do it.
I know there's another accept answer, but wanted to clarify why this is not: there's no way to convert a string to another type that's not a built-in value type using Convert.ChangeType(). This will use IConvertible.ToType() on the String type, which is implemented as calling internal method Convert.DefaultToType(), which throws an exception if the type to convert to is not a built-in value type. (referencesource.microsoft.com/#mscorlib/system/…)
3

I don't really think I understand what your are trying to archieve, but.. you mean a dynamic casting? Something like this:

 TypeDescriptor.GetConverter(typeof(String)).ConvertTo(myObject, typeof(Program)); 

Cheers.

Comments

0
string inputValue = myTxtBox.Text; PropertyInfo propInfo = typeof(MyClass).GetProperty(myPropertyName); Type propType = propInfo.PropertyType; propInfo.SetValue(myObject, Convert.ChangeType(inputValue, propType)); 

Here "myObject" is an instance of the class "MyClass", for which you want to set the property value generically.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.