How to Use Convert.ChangeType to convert string to any type in C#

By FoxLearn 2/4/2025 6:42:24 AM   193
You can utilize Convert.ChangeType() to transform a string into any type, like this:

For example:

double price = (double)Convert.ChangeType("19.99", typeof(double));

Normally, you'd directly call type-specific conversion methods, like int.Parse() or bool.Parse() when converting from a string to a specific type. However, in certain scenarios, it’s useful to use the generalized Convert.ChangeType() method instead of hardcoding individual conversion logic.

Parsing User Input into Correct Types

Let’s say you’re developing a program where users provide input, and you need to dynamically convert this input into various types based on user selection. Instead of writing separate parsing logic for each type, you can use Convert.ChangeType() to handle the conversion more flexibly.

For example, ParseInput() method - using Convert.ChangeType() for type conversion:

public static T ParseInput<T>(string input) where T : IConvertible
{
    if (string.IsNullOrWhiteSpace(input))
    {
        return default(T); // return default value for the type if input is empty
    }

    return (T)Convert.ChangeType(input, typeof(T));
}

Assume the user provides the following input through a form or command-line interface:

Username: JohnDoe
Age: 30
IsSubscribed: true
SignUpDate: 2025-02-01

The UserSettings class has properties corresponding to these inputs.

class UserSettings
{
    public string Username { get; set; }
    public int Age { get; set; }
    public bool IsSubscribed { get; set; }
    public DateTime SignUpDate { get; set; }
}

For example, how you can populate a UserSettings object dynamically by calling ParseInput():

static void Main(string[] args)
{
    var userSettings = new UserSettings()
    {
        Username = ParseInput<string>("JohnDoe"),
        Age = ParseInput<int>("30"),
        IsSubscribed = ParseInput<bool>("true"),
        SignUpDate = ParseInput<DateTime>("2025-02-01")
    };
}

When working with configuration settings in a .NET application, you often need to load values from app.config and convert them to the appropriate data types. However, settings in the app.config file are usually stored as strings, and you'll need to convert these strings to the correct type for your application to work properly. Furthermore, if a setting is missing, it's useful to return a default value for that type.

To handle the conversion of settings from app.config, we can create a utility method called GetSettingOrDefault(). This method will allow us to read a setting from app.config, attempt to convert it to the specified type, and return the default value if the setting is missing or invalid.

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

    // If the setting is missing, return the default value for the type
    if (setting == null)
    {
        return default(T);
    }

    // Convert the setting to the specified type
    return (T)Convert.ChangeType(setting, typeof(T));
}

In this method:

  • We retrieve the setting value from app.config using ConfigurationManager.AppSettings.
  • If the setting is not found, we return the default value for the type T.
  • If the setting is found, we convert it to the specified type using Convert.ChangeType().

This method leverages C# generics and the IConvertible interface, which allows for type-safe conversion of various types like string, int, bool, and DateTime.

For this example, let's assume the app.config file contains the following settings:

<appSettings>
    <add key="Url" value="https://foxlearn.com"/>
    <add key="Enabled" value="true"/>
    <add key="Retries" value="3"/>
    <add key="StartDate" value="2025-02-05 9:25 PM"/>
</appSettings>

These settings are strings, but we want to convert them into the appropriate types in our application. For example:

  • Url should be a string.
  • Enabled should be a bool.
  • Retries should be an int.
  • StartDate should be a DateTime.

We can create a ServiceSettings class that has properties matching the keys in app.config. This class will hold the converted values from the configuration file:

public class ServiceSettings
{
    public string Url { get; set; }
    public int Retries { get; set; }
    public bool Enabled { get; set; }
    public DateTime StartDate { get; set; }
}

Now, let's initialize the ServiceSettings object and use the GetSettingOrDefault() method to populate it with values from app.config.

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")
    };
}

In the Main method:

  • We create a new ServiceSettings object.
  • For each property, we call GetSettingOrDefault() with the appropriate type (string, bool, int, DateTime), passing the corresponding setting name from app.config.
  • GetSettingOrDefault() handles both the conversion and the fallback to default values when settings are missing.

By using the Convert.ChangeType() method and GetSettingOrDefault(), we can easily load settings from app.config and convert them to the appropriate types.

Convert.ChangeType() Works with Any IConvertible Type

In above example, I demonstrated how Convert.ChangeType() can be used to convert strings into the correct types. While the most common use case involves converting from a string to another type, it can also handle conversions between any types that implement the IConvertible interface.

To make an object convertible, implement the IConvertible interface in your class and define how it can be converted to other types.