The generics can generate a function AreEqual(string, string)
. This is a closer match than AreEqual(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:
using System.Diagnostics;
namespace ConsoleSandbox
{
interface IBar
{
}
class Program
{
static void Foo<T>(T obj1) where T: IBar
{
Trace.WriteLine("Inside Foo<T>");
}
static void Foo(object obj)
{
Trace.WriteLine("Inside Foo Object");
}
static void Main(string[] args)
{
Foo("Hello");
}
}
}
Even HERE it will choose the generic version over the non-generic version. And then you get this error:
The type 'string' cannot be used as type parameter 'T' in the generic
type or method 'ConsoleSandbox.Program.Foo(T)'. There is no
implicit reference conversion from 'string' to 'ConsoleSandbox.IBar'.
But if you add a function Foo(string obj1)
it will work.