简体   繁体   中英

Passing null value to overloading method where Object and String as param in C#

I have two overloaded methods like below

 public class TestClass
    {

        public void LoadTest(object param)
        {
            Console.WriteLine("Loading object...");
        }
        public void LoadTest(string param)
        {
            Console.WriteLine("Loading string...");
        }

    }

After calling this method like below it will show the output as Loading string... Please explain how .net handle this scenario?

 class Program
    {
        static void Main(string[] args)
        {       
            var obj=new TestClass();
            obj.LoadTest(null);
           // obj.LoadType(null);
            Console.ReadLine();
        }
    }

null is a valid string .

It will try to match the most specific type and string is more specific than object

Depending on your use you should probably remove the parameter totally in the object overload.

The C# compiler takes the most specific overload possible.

As string is an object , and it can have the value of null , the compiler deems string to be more specific.

This is just the way C# compiler prioritizes to determine which method is better to call. There is one rule:

If method A has more specific parameter types than method B, then method A is better than method B in overload case.

In your case, apparently string is more specified than object , that is why LoadTest(string param) is called.

You can refer 7.5.3.2 Better function member in C# language specification to get more understanding.

because compiler takes the closest possible specific method that can be accessed (null to string is closer than null to object) that is available. And in this case as both as overload with string is closer, that is why it is called.

This is what MSDN has to say

Once the candidate function members and the argument list have been identified, the selection of the best function member is the same in all cases:

  1. Given the set of applicable candidate function members, the best function member in that set is located.

  2. If the set contains only one function member, then that function member is the best function member.

  3. Otherwise, the best function member is the one function member that is better than all other function members with respect to the given argument list, provided that each function member is compared to all other function members using the rules in Section 7.4.2.2.

  4. If there is not exactly one function member that is better than all other function members, then the function member invocation is ambiguous and a compile-time error occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM