What are the priority rules for resolving method overloads in C #?

I am writing a serializer in which I want to make extensive use of method overloads to serialize type objects derived from IEnumerable<T> , IDictionary<K,V> etc.

I also intend to use the dynamic keyword so that the CLR selects the correct overload based on the type of runtime of the object to be serialized.

Take a look at this piece of code:

 void Serialize<TKey, TValue>(IDictionary<TKey, TValue> dictionary) { Console.WriteLine("IDictionary<TKey, TValue>"); } void Serialize<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items) { Console.WriteLine("IEnumerable<KeyValuePair<TKey, TValue>>"); } void Serialize<T>(IEnumerable<T> items) { Console.WriteLine("IEnumerable<T>"); } 

And I want to do this:

 void CallSerialize(object obj) { Serialize(obj as dynamic); //let the CLR resolve it at runtime. } 

Now, based on the obj time type, the correct overload will be called. For instance,

 //Test code CallSerialize(new List<int>()); //prints IEnumerable<T> 

In this case, the third overload is called up and the justification is quite simple: this is only a viable option.

However, if I do this:

 CallSerialize(new Dictionary<int,int>()); //prints IDictionary<TKey, TValue> 

It causes the first overload. I do not quite understand this. Why does it allow the first overload when all three overloads are viable parameters ?

In fact, if I delete the first, the second overload is called, and if I delete the first and second overload, the third overload is called.

What are the priority rules for resolving method overloads?

+4
source share
1 answer

Rules to allow method overloading will attempt to select a method header with the most specific type match. Here you can learn more about overload resolution and here I think your case.

From MSDN:

Given the list of arguments A with a set of argument types {A1, A2, ..., AN} and two applicable members of the function MP and MQ with parameter types {P1, P2, ..., PN} and {Q1, Q2, .. ., QN}, MP is defined as a better member of the function than MQ if

  • for each argument, the implicit conversion from AX to PX is no worse than the implicit conversion from AX to QX, and

  • for at least one argument, converting from AX to PX is better than converting from> AX to QX.

When performing this assessment, if MP or MQ are applicable in extended form, then PX or QX refers to the parameter in the extended form of the parameter list.

+6
source

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


All Articles