How to convert string to any type

C#GenericsReflection

C# Problem Overview


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

C# Solutions


Solution 1 - C#

using System.ComponentModel;

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

Solution 2 - C#

Try Convert.ChangeType

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

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDJPBView Question on Stackoverflow
Solution 1 - C#LeeView Answer on Stackoverflow
Solution 2 - C#SWekoView Answer on Stackoverflow
Solution 3 - C#vtortolaView Answer on Stackoverflow