0

Given the following code;

using System;

public class Program
{
    class Example
    {
        static void F(object x) => Console.WriteLine("F(object)");
        static void F<T>(T x) => Console.WriteLine($"F<T>(T), T is {typeof(T)}");
        public static void UsageExample()
        {
            F("abc");
        }
    }

    public static void Main()
    {
        Example.UsageExample();
    }
}

I don't understand how the compiler is selecting which function to invoke for method; F("abc");. What is the criteria, how I did not implicitly invoke F("abc").

When I executed the app, I expected F("abc") to return;

"F(object)" -- "abc" is an object and a System.String

but it return;

"F(T), T is System.String"

instead; I did not invoke F<string>("abc") so how did it know to use;

static void F(T x) => Console.WriteLine($"F(T), T is {typeof(T)}"); ??

In other words, why doesn't F(object x) capture F("abc") before static void F<T>(T x)?

  • Side note: "the runtime is selecting which function to invoke" - overloads are resolved at compile time (except `dynamic`), so really there is no "runtime selecting" in the code. – Alexei Levenkov Mar 04 '23 at 01:35
  • I understand now, F is a better match than F by definition of static void F(T x) by it seems like F(object x) should capture everything before F(T x). – user2237631 Mar 04 '23 at 02:12
  • 1
    @user2237631 - The compiler chooses the most derived overload, so a generic `T` is more derived than `object`. – Enigmativity Mar 04 '23 at 03:21
  • https://csharpindepth.com/articles/Overloading – Enigmativity Mar 04 '23 at 04:00

0 Answers0