Runtime Conversions with Convert.ChangeType

Sometimes we may need to convert to one type to another at runtime but we don’t know the type in advance. In this situations we can use Convert.ChangeType() method.
In this below code i had converted the value 100 which is a string and this value converted to int and double at runtime
object initialValue = "100";
Type targetType = typeof (int);
object convertedValue = Convert.ChangeType(initialValue, targetType);
Type convertedType = convertedValue.GetType();
targetType = typeof(double);
convertedValue = Convert.ChangeType(initialValue, targetType);
convertedType = convertedValue.GetType();

Enjoy Coding…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s