What I want to do is the following:
- Have several classes, one of which is a base one for the rest. All those classes are not self-made.
- Have a function overridden for each of the classes including the base one.
- Have a single generic function that uses the set of overridden functions. The generic function constrains its type parameter to be based on the base class.
Here's the code:
public class Program
{
class Base
{
}
class A : Base
{
}
class B : Base
{
}
private static int Id(Base obj)
{
return 0;
}
private static int Id(A obj)
{
return 1;
}
private static int Id(B obj)
{
return 2;
}
private static int GetId<T>(T obj) where T : Base
{
return Id(obj);
}
public static void Main(string[] args)
{
int idBase = GetId(new Base());
int idA = GetId(new A());
int idB = GetId(new B());
// expected | idBase=0, idA=1, idB=2
// but getting | idBase=0, idA=0, idB=0
Console.WriteLine($"idBase={idBase}, idA={idA}, idB={idB}");
}
}
Since C# doesn't support explicit specialization I cannot use a template function and specialize it for each of the instances, but probably it is needless to use such since a set of overridden such would do even better work. Yet, the correct overrides are not called but only the one for the base class. Even the IDE is giving me hints that the rest are not used. Tell me what I am missing.