I wonder if it is in any way possible to specialize generic interface methods somehow in C#? I have found similar questions, but nothing exactly like this. Now I suspect tha
You can do it by introducing additional type information (e.g. implementing an interface). Here is an example.
// no need to modify the original interface
public interface IStorage
{
void Store(T data);
}
Implementation with specialization based on a generic interface
public class Storage : IStorage,
Storage.ISpecializedFor,
Storage.ISpecializedFor
{
// a private interface to provide additional type info
private interface ISpecializedFor
{
void Store(T data);
}
public void Store(T data)
{
// resolve specialization
if (this is ISpecializedFor specialized)
{
specialized.Store(data);
}
else
{
// unspecialized implementation goes here
Console.WriteLine("Unspecialized");
}
}
// specialized implementation
void ISpecializedFor.Store(int data)
{
Console.WriteLine("Specialized for int");
}
void ISpecializedFor.Store(double data)
{
Console.WriteLine("Specialized for double");
}
}
Results
void Main()
{
IStorage storage = new Storage();
storage.Store("hello"); // prints "Unspecialized"
storage.Store(42); // prints "Specialized for int"
storage.Store(1.0); // prints "Specialized for double"
}