In my code (.NET6.0) I have a class with two very similar methods. One is not generic, but has a second optional parameter. Second method is generic with only one (generic) parameter.
var c = new C();
var stringParam = "normal string";
dynamic dynamicParam = stringParam;
c.M(stringParam);
c.M(dynamicParam);
public interface II { }
public class C
{
public void M(string param, TimeSpan? dt = null) => Console.WriteLine("Not generic");
public void M<T>(T param) where T : II => Console.WriteLine("Generic");
}
When I run this code, it fails at the calling of method M with dynamicParam. I get a runtime exception
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M(T)'. There is no implicit reference conversion from 'string' to 'II'.'
What I don't understand is why the runtime does not in both cases use the non generic method, because I don't call it in a generic way.
When I remove second optional nullable parameter from the first method, it works - non generic method is called in both cases.
When I remove second (generic) method, it also works.
When I compile the code and check it with ILSpy, both methods look really different. So why does it not work with both methods as they are?
I have checked other SO questions with the same error message, and I believe that my issue has a different cause.