Passing a null value to the overload method when Object and String as a parameter 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, as shown below, it will display as Loading Row .... Explain how .net handles this script?

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

The C # compiler provides the most specific overload.

Since string is an object , and it can be null , the compiler considers string more specific.

+4
source

null is a valid string .

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

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

+4
source

This is exactly how the C # compiler prioritizes to determine which method is best 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 case of overload.

In your case, obviously, string larger than object , so LoadTest(string param) called.

You can refer to 7.5.3.2 A more efficient member of a function in the C # language specification to gain more understanding.

+3
source

because the compiler uses the maximum possible concrete method that can be accessed (the null value for the string is closer than null to the object), which is available. And in this case, since overloading with the string is closer, therefore it is called.

This is what MSDN has to say.

After the candidate members and the list of arguments are identified, the choice of the best member of the function will be the same in all cases:

  • Given the set of applicable candidate candidate members, the best member of the function in this set is found.

  • If a collection contains only one member of a function, then this member of the function is the best member of the function.

  • Otherwise, the best member of the function is one member of the function that is better than all other members of the function relative to the given list of arguments, provided that each member of the function is compared with all other members of the function using the rules in section 7.4.2.2.

  • If there is no one member of the function that is better than all the other members of the function, then the call to the member function is ambiguous and a compile-time error occurs.

+2
source

Source: https://habr.com/ru/post/952006/


All Articles