Type inference for type arguments to common methods

I am new to Stack Overflow, so please take it easy! I am reading C # in Depth, but I came across a script that I suppose is not covered. A quick search on the Internet did not return any results.

Let's 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 called? Is a generic method invoked with an argument of the type that is invoked, or is it not a generic method invoked with method arguments that are implicitly mapped to System.Object?

Hope my question is clear. Thanks in advance for any advice.

+5
source share
1 answer

AreEqual(string, string). , AreEqual(object, object), .

, , .

:

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");
        }
    }
}

- . :

'string' 'T' 'ConsoleSandbox.Program.Foo(T)'. 'string' 'ConsoleSandbox.IBar'.

Foo(string obj1), .

+5

All Articles