68

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

125
using System.ComponentModel;

TypeConverter typeConverter = TypeDescriptor.GetConverter(propType);
object propValue = typeConverter.ConvertFromString(inputValue);
4
  • 1
    I'm surprised that this one gets the upvotes compared to Convert.ChangeType. Feb 25, 2016 at 22:37
  • 19
    Probably because ChangeType tries to cast, not convert. For example, ChangeType can't go from String to Nullable<Int64> - TypeConverter can.
    – efdee
    Jul 6, 2016 at 8:59
  • Nor can it handle automatic parsing of enums Apr 15, 2019 at 17:24
  • 1
    Convert.ChangeType also fails for string -> Guid
    – Bassie
    Jan 13, 2022 at 6:52
16

Try Convert.ChangeType

object propvalue = Convert.ChangeType(inputValue, propType);
5
  • 2
    This is really a comment, not an answer to the question. Please use "add comment" to leave feedback for the author. Aug 22, 2012 at 1:03
  • @SteveGuidi: Default already edited the answer in the meantime, tnx to both.
    – SWeko
    Aug 22, 2012 at 12:48
  • 2
    @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.
    – default
    Aug 23, 2012 at 6:42
  • This is really the the proper way to do it. Feb 25, 2016 at 22:34
  • 1
    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/…) Apr 22, 2020 at 10:19
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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.