I'm a newby to Stack Overflow so please go easy on me! I'm reading C# in Depth but I've come across a scenario that I don't believe is covered. A quick search of the web didn't throw up any results either.
Say I define the following overloaded methods:
void AreEqual<T>(T expected, T actual)
void AreEqual(object expected, object actual)
If I call AreEqual()
without specifying a type argument:
AreEqual("Hello", "Hello")
Is the generic or non-generic version of the method invoked? Is the generic method invoked with the type argument being inferred, or is the non-generic method invoked with the method arguments being implicitly cast to System.Object
?
I hope my question is clear. Thanks in advance for any advice.
The generics can generate a function
AreEqual(string, string)
. This is a closer match thanAreEqual(object, object)
, so therefore the generic function is chosen.Interestingly, the compiler will choose this generic function even if it results in a constraint violation error.
Look at this example:
Even HERE it will choose the generic version over the non-generic version. And then you get this error:
But if you add a function
Foo(string obj1)
it will work.