When trying to call this function in my code i get the error in the title. Also Operator \'+=\' cannot be applied to the operands of type \'int\' and \'T\'
p
It knows not how to add your T
to a numeric since it doesnt know what the type of T
is going to be.
t += Convert.ToInt32(value);
But since you are adding int
to int
and returning int
then why not just ditch the generic parameter and make it
public int Change(Stats type, int value)
and if you want different behaviour for different types and really want the same method name, instead of testing the type just do:
public int Change(Stats type, string value)
public int Change(Stats type, DateTime value)
I had a very similar problem. It is not exactly the problem asked here, but it could be a start point:
private T GetXValue<T>(XElement xElem, string name)
{
try
{
object o = xElem.Element(name).Value;
return (T)Convert.ChangeType(o, typeof(T));
}
catch
{
return (T)Activator.CreateInstance(typeof(T), null);
}
}
you can try casting the value like this ...
t += (int)value;
or
t+= Convert.ToInt32(value);
The error you are getting makes sence. While you call the method with int
as the type, the compiler doesn't know that will be the case.
To compile the method as it is, the compiler will need to prove that the operations you do on T will be valid for all T - which is clearly not the case.
You can set constraint:
public int Change<T>(Stats type, T value) where T : IConvertible
Then:
var intValue = value.ToInt32();
Or another way (object cast is necessary not typo)
t += (int)(object)value;
Or use dynamic, by using dynamic you can do more, such as implicit casts
Or use Int32 - Int32 and int are both struct internally. No performance loss