dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.27k stars 4.73k forks source link

Please add TryParse and ChangeType generic to System.Convert class #5599

Closed Thaina closed 4 years ago

Thaina commented 8 years ago

In addition to ToInt32() and all other parsing things. System.Convert should have generic parser

public static bool TryParse<T>(string s,out T v) where T : struct,IConvertible,IFormattable,IComparable<T>,IEquatable<T>
{
    return T.TryParse(s,out v);
}

public static T ChangeType<T>(object obj) where T : IConvertible
{
    T v;
    ChangeType<T>(obj,out v);
    return v;
}

public static bool ChangeType<T>(object obj,out T v) where T : IConvertible
{
    try
    {
        /// Should be better algorithm instead of try/catch + unboxing
        v = (T)Convert.ChangeType(obj,typeof(T));
        return true;
    }
    catch
    {
        v = default(T);
        return false;
    }
}

/// usage

int i;
if(Convert.TryParse("123456",out i))
    DoSomething(i);

double d;
if(Convert.ChangeType(i,out d))
    DoSomething(d);
svick commented 8 years ago

You seem to be asking for a new API, so I think you should follow the API review process by posting this issue to the corefx repo.

karelz commented 7 years ago

Please follow @svick's guidance and file API proposal in corefx repo.