Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to any type

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

like image 281
DJPB Avatar asked May 27 '10 16:05

DJPB


People also ask

How can a string be converted to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.


2 Answers

using System.ComponentModel;  TypeConverter typeConverter = TypeDescriptor.GetConverter(propType); object propValue = typeConverter.ConvertFromString(inputValue); 
like image 115
Lee Avatar answered Sep 25 '22 18:09

Lee


Try Convert.ChangeType

object propvalue = Convert.ChangeType(inputValue, propType); 
like image 39
SWeko Avatar answered Sep 26 '22 18:09

SWeko