Tag Archives: parse int

Función con tipos genericos

La comodidad de usar tipos genéricos:

private T ParseToNumber<T>(string value, Type type)
{
    if (string.IsNullOrEmpty(value))
    {
        return (T)Convert.ChangeType(0, typeof(T));
    }
    if (type == typeof(short))
    {
        return (T)Convert.ChangeType(short.Parse(value), typeof(T));
    }
    if (type == typeof(ulong))
    {
        return (T)Convert.ChangeType(ulong.Parse(value), typeof(T));
    }
    if (type == typeof(ushort))
    {
        return (T)Convert.ChangeType(ushort.Parse(value), typeof(T));
    }
    return (T)Convert.ChangeType(0, typeof(T));
}

 

La llamada:

var myNumber= this.ParseToNumber<short>("1", typeof(short)),