C# – Cannot implicitly convert type ‘Int’ to ‘T’

cgenerics

I can call Get<int>(Stat); or Get<string>(Name);

But when compiling I get:

Cannot implicitly convert type 'int' to 'T'

and the same thing for string.

public T Get<T>(Stats type) where T : IConvertible
{
    if (typeof(T) == typeof(int))
    {
        int t = Convert.ToInt16(PlayerStats[type]);
        return t;
    }
    if (typeof(T) == typeof(string))
    {
        string t = PlayerStats[type].ToString();
        return t;
    }
}

Best Answer

You should be able to just use Convert.ChangeType() instead of your custom code:

public T Get<T>(Stats type) where T : IConvertible
{
    return (T) Convert.ChangeType(PlayerStats[type], typeof(T));
}