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);
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>());
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?