I am working with a code that contains following overloaded method in generic class:
public class A<T>
{
public void Process(T item) { /*impl*/ }
public void Process(string item) { /*impl*/ }
}
When parametrizing the class for string do I lose the possibility to call the version with generic parameter?
var a = new A<string>();
a.Process(""); //Always calls the non-generic Process(string)
There is one way I just discovered, but it’s a bit cross-eyed. Because generics and overloading get resolved in build time, you can define a generic method:
Now, if we do the following:
You can use a similar trick if you define a generic class instead of a generic method. The important thing is that the parameter you transfer to
ProblemOverloadneeds to be of typeTrather than typestringin the invocation. After all, the methodCallGenericOverloadknows it’s getting aTat build time, so it’s going to bind to the overload that accepts the parameter. It doesn’t matter that it’s actually going to get astringat runtime.