C# – Use Convert.ChangeType to convert string to any type

You can use Convert.ChangeType() to convert from a string to any type, like this:

bool enabled = (bool)Convert.ChangeType("true", typeof(bool));
Code language: C# (cs)

Normally you’d call the specific type converter method, such as when you’re converting a string to an int. However, sometimes it makes sense to use the generalized type converter method – Convert.ChangeType() – instead of hardcoding the calls to specific type converter methods.

I’ll show an example of when it makes sense to use Convert.ChangeType().

Example – Converting settings from app.config to the right types

Let’s say you want to load values from app.config and convert each value to the appropriate type. If the setting is missing, you want the default value for that type. This example shows how to implement this by using Convert.ChangeType().

GetSettingOrDefault() method – use Convert.ChangeType for type conversion

This is reading from app.config and converting to the type specified by the generic T parameter.

public static T GetSettingOrDefault<T>(string settingName) where T : IConvertible
	var setting = ConfigurationManager.AppSettings[settingName];

	if (setting == null)
		return default(T);

	return (T)Convert.ChangeType(setting, typeof(T));
Code language: C# (cs)

ServiceSettings class

In app.config I have four settings.

	<add key="Url" value="makolyte.com"/>
	<add key="Enabled" value="true"/>
	<add key="Retries" value="3"/>
	<add key="StartDate" value="2020-07-11 8:25 AM"/>
Code language: HTML, XML (xml)

The ServiceSettings class has properties that represent the settings in app.config.

class ServiceSettings
	public string Url { get; set; }
	public int Retries { get; set; }
	public bool Enabled { get; set; }
	public DateTime StartDate { get; set; }
Code language: C# (cs)

Init ServiceSettings with GetSettingOrDefault()

Here I’m calling GetSettingOrDefault(), specifying the setting name and the type to convert to.

static void Main(string[] args)
	var serviceSettings = new ServiceSettings()
		Url = GetSettingOrDefault<string>("Url"),
		Enabled = GetSettingOrDefault<bool>("Enabled"),
		Retries = GetSettingOrDefault<int>("Retries"),
		StartDate = GetSettingOrDefault<DateTime>("StartDate")
Code language: C# (cs)

Convert.ChangeType() can convert anything that implements IConvertible

In this article I explained how to use Convert.ChangeType() to convert from a string to another object. That is the most common use case.

However, you can actually use this method to convert an object to any other type, as long as it is convertible to that type. To make it convertible, you need to implement the IConvertible interface in your class and explicitly define how this object can be converted to the target type.

Leave a Comment