简体   繁体   中英

Default value of a Type in C#

I am using the following code to Convert string to any type. I have hardcoded the type as double here but it can be integer or long, bool, or...

Now when the string is empty or null this code fails, how can I return the default value of the passed type in this case?

        var result = ConvertFromString(item, typeof(double));

        private object ConvertFromString(string str, Type type)
        {
            return Convert.ChangeType(str, type);
        }

You could use Activator.CreateInstance to create an instance of a value type:

private static object ConvertFromString(string str, Type type)
{
    if (string.IsNullOrEmpty(str))
        return type.IsValueType ? Activator.CreateInstance(type) : null;

    return Convert.ChangeType(str, type);
}

ConvertFromString(null, typeof(int)) will then return 0 (or default(int) ).

I would make your method generic to return the actual requested type instead of object, to be more type safe. You will find the actual answer to the default thing below too.

[TestMethod]
public void MyTestMethod()
{
    // to be sure that the decimal sign below is "." and not e.g. "," like in my culture :)
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

    // test
    var result = ConvertFromString<double>("3.14");
    Assert.AreEqual(3.14, result);

    // test
    result = ConvertFromString<double>("blabla");
    Assert.AreEqual(0, result);
}


private TRet ConvertFromString<TRet>(string str)
{
    TRet ret = default(TRet);

    try
    {
        ret = (TRet)Convert.ChangeType(str, typeof(TRet));
    }
    catch (Exception ex)
    {
        // handle error as you wish
    }

    return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM