DJPB
DJPB

Reputation: 5819

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

Upvotes: 69

Views: 44951

Answers (4)

Chintan Ranpura
Chintan Ranpura

Reputation: 1

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.

Upvotes: 0

Lee
Lee

Reputation: 144226

using System.ComponentModel;

TypeConverter typeConverter = TypeDescriptor.GetConverter(propType);
object propValue = typeConverter.ConvertFromString(inputValue);

Upvotes: 127

SWeko
SWeko

Reputation: 30942

Try Convert.ChangeType

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

Upvotes: 16

vtortola
vtortola

Reputation: 35963

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.

Upvotes: 3

Related Questions