I am (trying) to learn about generics and I thought I understood them. I have the following code for the generic class:
/// <summary>
/// generics
/// </summary>
class Point<T> where T : IConvertible
{
public T X;
NumberFormatInfo nf = NumberFormatInfo.CurrentInfo;
public double Subtract(Point<T> pt)
{
return (X.ToDouble(nf) + pt.X.ToDouble(nf));
}
}
and in the Main(), I can create the objects fine:
Point<int> pt = new Point<int>();
Point<double> pt2 = new Point<double>();
Point<string> pt3 = new Point<string>();
pt.X = 10;
pt2.X = 10;
pt3.X = "10";
Now, I can run the Subtract Method on two ints, doubles or even strings, but I can’t run on mixed, which I thought I would be able to because of the .ToDouble conversion.
If I try to run Console.WriteLine(pt.Subtract(pt2)); I get the following errors:
Error 1 The best overloaded method match for Date.Point<int>.Subtract(Date.Point<int>)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'Date.Point<double>' to 'Date.Point<int>'
The code itself is not so important as I am simply trying to understand/learn generics, so I would just like to understand what is wrong here and why it wouldn’t work…. The actual method is not that important/will not be used.
Your method signature:
Asks for a
Pointof generic typeT, which matches the generic type in your class definition:That means it’s asking for the same type.
You can specify a different generic type to allow it to mix different types:
Note, however, that since the actual type of
Ucan be inferred from thePoint<U>argument you pass, you can call your method in the same way without needing to specify the type: