Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'Int' to 'T'

Tags:

c#

generics

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;     } } 
like image 578
David W Avatar asked Nov 17 '11 17:11

David W


1 Answers

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)); } 
like image 147
BrokenGlass Avatar answered Sep 23 '22 01:09

BrokenGlass