I'm trying to write generic algorithms in C# that can work with geometric entities of different dimension.
In the following contrived example I have Point2 and Point3, both implementing a simple IPoint interface.
Now I have a function GenericAlgorithm that calls a function GetDim. There are multiple definitions of this function based on the type. There is also a fall-back function that is defined for anything that implements IPoint.
I initially expected the output of the following program to be 2, 3. However, it is 0, 0.
interface IPoint {
public int NumDims { get; }
}
public struct Point2 : IPoint {
public int NumDims => 2;
}
public struct Point3 : IPoint {
public int NumDims => 3;
}
class Program
{
static int GetDim<T>(T point) where T: IPoint => 0;
static int GetDim(Point2 point) => point.NumDims;
static int GetDim(Point3 point) => point.NumDims;
static int GenericAlgorithm<T>(T point) where T : IPoint => GetDim(point);
static void Main(string[] args)
{
Point2 p2;
Point3 p3;
int d1 = GenericAlgorithm(p2);
int d2 = GenericAlgorithm(p3);
Console.WriteLine("{0:d}", d1); // returns 0 !!
Console.WriteLine("{0:d}", d2); // returns 0 !!
}
}
OK, so for some reason the concrete type information is lost in GenericAlgorithm. I don't fully understand why this happens, but fine. If I can't do it this way, what other alternatives do I have?