In C#, I'd like to have a method of my generic class behave in different ways, using something akin to explicit template specialization
I see from a related post that such a thing might be possible in C#, using extensions, but my code is not behaving as desired: I want one behaviour for Thing<int>::Method()
and another behaviour when <T>
is anything other than <int>
.
I have
using System;
public interface IThing
{
void Method();
}
public class Thing<T> : IThing
{
public void Method()
{
this.Specialization<T>();
}
}
public static class ThingExtensions
{
public static void Specialization<T>(this Thing<T> cls)
{
Console.WriteLine("Thing<T> specialization");
return;
}
public static void Specialization(this Thing<int> cls)
{
Console.WriteLine("Thing<int> specialization");
return;
}
}
public class Program
{
public static void Main()
{
var t = new Thing<float>();
t.Method();
t.Specialization();
var i = new Thing<int>();
i.Method();
i.Specialization();
}
}
But this outputs
Thing<T> specialization
Thing<T> specialization
Thing<T> specialization
Thing<int> specialization
Rather than
Thing<T> specialization
Thing<T> specialization
Thing<int> specialization
Thing<int> specialization
The obvious question "why not just call Specialization<T>
rather than Method
?" is hopefully answered by my inclusion of the interface class - I am trying to fit into its framework.
I can see that Specialization<T>
is a match for Specialization<int>
, but I'm surprised that the latter is not regarded as a better match!