Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top