Method overload. How the compiler decide which to use? - c#

I have 2 methods.
1. public void Log(object tolog, string Instance)
2. public void Log(params object[] tolog)
And I call Log like this, where tolog1 is a object
Log(tolog1,"Hello")
I'm confused as to why the compiler has chosen the second overload. What conditions would cause this?

Your call Log(tolog1,"Hello") would use the method Log(object tolog, string Instance) that is because of Overloading Resolution Rules (7.4.2).
Given the list of arguments your first method overload Log(object tolog, string Instance) is a more suitable/closer candidate and compiler can determine that because of the rules specified:
Overloading Resolution Rules (7.4.2)
Given the set of applicable candidate function members, the best function member in that set is located.
If the set contains only one function member, then that function member is the best function member.
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.
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
Under Section 7.4.2.2 You will see:
Given an argument list A with a set of argument types {A1, A2, ...,
AN} and two applicable function members MP and MQ with parameter types
{P1, P2, ..., PN} and {Q1, Q2, ..., QN}, MP is defined to be a better
function member than MQ if
for each argument, the implicit conversion from AX to PX is not worse than the implicit conversion from AX to QX, and
for at least one argument, the conversion from AX to PX is better than the conversion from AX to QX.
When performing this evaluation, if MP or MQ is applicable in its
expanded form, then PX or QX refers to a parameter in the expanded
form of the parameter list.

In short, the compiler chooses the type which is closer i.e. the object that is at highest level of Hierarchy / Inheritance.
In your case, Log(tolog1,"Hello"), tolog1 satisfies both the overloads
Log(params object[] tolog) and Log(object tolog, string Instance) but in case of second parameter "Hello" the compiler chooses Log(object tolog, string Instance) As System.String is closer to "Hello" than System.Object

Related

Why is the compiler choosing the generic method over specific one?

I have this service interface.
public interface IService
{
Task SetAsync(string key, string value, TimeSpan? expiration = null);
Task SetAsync<T>(string applicationName, string key, T value, TimeSpan? expiration = null);
}
I would like to call the first method by doing so.
service.SetAsync("Key", "Value", TimeSpan.FromMinutes(1));
The method call matches 100% the contract of the first method. Yet the compiler chooses the second method by assuming TimeSpan is my generic type.
Why is this happening?
This is following the rules for "Better function member" in the ECMA C# 5 standard, section 12.6.4.3:
For the purposes of determining the better function member, a stripped-down argument list A is constructed containing just the argument expressions themselves in the order they appear in the original argument list.
Parameter lists for each of the candidate function members are constructed in the following way:
The expanded form is used if the function member was applicable only in the expanded form.
Optional parameters with no corresponding arguments are removed from the parameter list
The parameters are reordered so that they occur at the same position as the corresponding argument in the argument list.
So at that point, we're comparing these two methods, effectively:
Task SetAsync(string key, string value, TimeSpan? expiration);
Task SetAsync<T>(string applicationName, string key, T value);
(In the generic method version, the expiration parameter does not have a corresponding argument, so it's removed from the parameter list.)
The argument list is "Key", "Value", TimeSpan.FromMinutes(1), and T is inferred to be TimeSpan.
Next:
Given an argument list A with a set of argument expressions { E1, E2, ..., EN } and two applicable function members MP and MQ with parameter types { P1, P2, ..., PN } and { Q1, Q2, ..., QN }, MP is defined to be a better function member than MQ if
for each argument, the implicit conversion from EX to QX is not better than the implicit conversion from EX to PX, and
for at least one argument, the conversion from EX to PX is better than the conversion from EX to QX.
For the first two parameters, there's no difference - because they're string everywhere.
For the third parameter, the conversion for the non-generic method is from TimeSpan to TimeSpan?, and for the generic method it's from TimeSpan to TimeSpan (because T is TimeSpan).
The identity conversion of TimeSpan to TimeSpan is "better" (as per the rules of 12.6.4.4) than the implicit conversion of TimeSpan to TimeSpan?, so for that parameter, the generic method is "better"... and there's no parameter for which the non-generic method is "better", therefore overall the generic method is better.
If neither method had been found to be "better" in this stage (e.g. due to a parameter type of TimeSpan instead of TimeSpan? for the optional parameter) then the non-generic method would have been determined to be "better" by the tie-break rules following this stage. But by that point, the generic method has already been selected.

C# params argument selection when used twice

I'm curious why neither of the following DoInvoke methods can be called with only one params:
public class foo {
private void bar(params object[] args) {
DoInvoke(args);
}
//Error: There is no argument given that corresponds to the required formal parameter 'args' of 'foo.DoInvoke(Delegate, object[])'
private void DoInvoke(Delegate d, object[] args) {
d.DynamicInvoke(args);
}
//Error: Argument 1: cannot convert from 'object[]' to 'System.Delegate'
private void DoInvoke(Delegate d, params object[] args) {
d.DynamicInvoke(args);
}
}
I already found a way that doesn't abuse params. I'm curious why params are not expanded here.
I was able to do something similar in Lua, hence my attempt. I know Lua is far less strict, but I'm not sure which C# rule I'm breaking by doing this.
I'm curious why neither of the following DoInvoke methods can be called with only one params:
Short version: the first can't, because it has two non-optional parameters and because you're passing a value of the wrong type for the first non-optional parameter. The second can't, but only because the value you are trying to pass for the single non-optional parameter is of the wrong type; the second parameter is optional and so may be omitted as you've done.
You seem to be under the impression that in your method declaration private void bar(params object[] args), the presence of the params keyword makes the args variable somehow different from any other variable. It's not. The params keyword affects only the call site, allowing (but not requiring) the caller to specify the array elements of the args variable to be specified as if they were individual parameters, rather than creating the array explicitly.
But even when you call bar() that way, what happens is that an array object is created and passed to bar() as any other array would be passed. The variable args inside the bar() method is just an array. It doesn't get any special handling, and the compiler won't (for example) implicitly expand it to a parameter list for use in passing to some other method.
I'm not familiar with Lua, but this is somewhat in contrast to variadic functions in C/C++ where the language provides a way to propagate the variable parameter list to callees further down. In C#, the only way you can directly propagate a params parameter list is if the callee can accept the exact type of array as declared in the caller (which, due to array type variance in C#, does not always have to be the exact same type, but is still limited).
If you're curious, the relevant C# language specification addresses this in a variety of places, but primarily in "7.5.1.1 Corresponding parameters". This reads (from the C# 5 specification…there is a draft C# 6 specification, but the C# 5 is basically the same and it's what I have a copy of):
For each argument in an argument list there has to be a corresponding parameter in the function member or delegate being invoked.
It goes on to describe what "parameter list" is used to validate the argument list, but in your simple example, overload resolution has already occurred at the point this rule is being applied, and so there's only one parameter list to worry about:
• For all other function members and delegates there is only a single parameter list, which is the one used.
It goes on to say:
The corresponding parameters for function member arguments are established as follows:
• Arguments in the argument-list of instance constructors, methods, indexers and delegates:
o A positional argument where a fixed parameter occurs at the same position in the parameter list corresponds to that parameter. [emphasis mine]
o A positional argument of a function member with a parameter array invoked in its normal form corresponds to the parameter array, which must occur at the same position in the parameter list.
o A positional argument of a function member with a parameter array invoked in its expanded form, where no fixed parameter occurs at the same position in the parameter list, corresponds to an element in the parameter array.
o A named argument corresponds to the parameter of the same name in the parameter list.
o For indexers, when invoking the set accessor, the expression specified as the right operand of the assignment operator corresponds to the implicit value parameter of the set accessor declaration.
In other words, if you don't provide a parameter name in your argument list, arguments correspond to method parameters by position. And the parameter in the first position of both your called methods has the type Delegate.
When you try to call the first method, that method has zero optional parameters, but you haven't provided a second parameter. So you get an error telling you that your argument list, consisting of just a single argument (which by the above corresponds to the Delegate d parameter), does not include a second argument that would correspond to the object[] args parameter in the called method.
Even if you had provided a second argument, you would have run into the same error you get trying to call your second method example. I.e. while the params object[] args parameter is optional (the compiler will provide an empty array for the call), and so you can get away with providing just one argument in your call to the method, that one argument has the wrong type. Its positional correspondence is to the Delegate d parameter, but you are trying to pass a value of type object[]. There's no conversion from object[] to Delegate, so the call fails.
So, what's that all mean for real code? Well, that depends on what you are trying to do. What did you expect to happen when you tried to pass your args variable to a void DoInvoke(Delegate d, params object[] args) method?
One obvious possibility is that the args array contains as its first element a Delegate object, and the remainder of the array are the arguments to pass. In that case, you could do something like this:
private void bar(params object[] args) {
DoInvoke((Delegate)args[0], args.Skip(1).ToArray());
}
That should be syntactically valid with either of the DoInvoke() methods you've shown. Of course, whether that's really what you want is unclear, since I don't know what the call was expected to do.

Method overloaded with "params" keyword behavior [duplicate]

Say I have the following methods:
public static void MyCoolMethod(params object[] allObjects)
{
}
public static void MyCoolMethod(object oneAlone, params object[] restOfTheObjects)
{
}
If I do this:
MyCoolMethod("Hi", "test");
which one gets called and why?
It's easy to test - the second method gets called.
As to why - the C# language specification has some pretty detailed rules about how ambiguous function declarations get resolved. There are lots of questions on SO surrounding interfaces, inheritance and overloads with some specific examples of why different overloads get called, but to answer this specific instance:
C# Specification - Overload Resolution
7.5.3.2 Better function member
For the purposes of determining the
better function member, a
stripped-down argument list A is
constructed containing just the
argument expressions themselves in the
order they appear in the original
argument list.
Parameter lists for each of the
candidate function members are
constructed in the following way:
The expanded form is used if
the function member was applicable
only in the expanded form.
Optional parameters with no
corresponding arguments are removed
from the parameter list
The parameters are reordered
so that they occur at the same
position as the corresponding argument
in the argument list.
And further on...
In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are equivalent > (i.e. each Pi has an identity conversion to the corresponding Qi), the following
tie-breaking rules are applied, in order, to determine the better function member.
If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.
Otherwise, if MP is applicable in its normal form and MQ has a params array and is
applicable only in its expanded form, then MP is better than MQ.
Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ.
This can occur if both methods have params arrays and are applicable only in their
expanded forms.
The bolded tie-breaking rule seems to be what is applying in this case. The specification goes into detail about how the params arrays are treated in normal and expanded forms, but ultimately the rule of thumb is that the most specific overload will be called in terms of number and type of parameters.
The second one, the compiler will first try to resolve against explicitly declared parameters before falling back on the params collection.
This overload is tricky...
MyCoolMethod("Hi", "test") obviously calls the 2nd overload, but
MyCoolMethod("Hi"); also calls the 2nd overload. I tested this.
Maybe since both of the inputs are objects, the compiler assume anything passed in will be an array of objects and completely ignores the 1st overload.
It probably has to do with the Better function member resolution mentioned by womp
http://msdn.microsoft.com/en-us/library/aa691338(v=VS.71).aspx

Generic and non-generic method overload rules with type inference

Given the following two overloaded method signatures:
public B DoSomething<A,B>(A objOne, B objTwo)
public object DoSomething(object objOne, Type objType);
I would expect that calling this would call the second signature, but it does not:
var obj = new SomeType();
var type = typeof(SomeOtherType);
DoSomething(obj, type);
It seems to me that looking at the spec, the second overload is more applicable (has one exact type and lesser arity). But, it does not get called. Instead, the first overload is called with A as the type object and B as the type Type. Why is that and is there a way to call this method aside from either renaming the method or using named parameters?
EDIT:
Here are the parts of the spec I'm referring to in 7.5.3.2:
In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are equivalent (i.e. each Pi has an identity conversion to the corresponding Qi), the following tie-breaking rules are applied, in order, to determine the better function member.
If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.
...
Otherwise, if MP has more specific parameter types than MQ, then MP is better than MQ. Let {R1, R2, …, RN} and {S1, S2, …, SN} represent the uninstantiated and unexpanded parameter types of MP and MQ. MP’s parameter types are more specific than MQ’s if, for each parameter, RX is not less specific than SX, and, for at least one parameter, RX is more specific than SX:
A type parameter is less specific than a non-type parameter.
...
After your edit here is methods for compiler to choose between
DoSomething<SomeType,Type>(SomeType o, Type t)
DoSomething(object o,Type t);
As specification says about picking better function member:
Given an argument list A with a set of argument expressions { E1, E2,
..., EN } and two applicable function members MP and MQ with parameter
types { P1, P2, ..., PN } and { Q1, Q2, ..., QN }, MP is defined to be
a better function member than MQ if
• for at least one argument, the
conversion from EX to PX is better than the conversion from EX to QX.
Generic method have better conversion from SomeType to SomeType than non-generic's method conversion from SomeType to object. If non-generic method would be defined as
DoSomething(SomeType o, Type t);
then there would not be any arguments with better conversion, and you'll fall into case:
In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …,
QN} are equivalent
Where first rule would pick non-generic method:
• If MP is a non-generic method and MQ is a generic method, then MP is
better than MQ.
NOTE: Before you edited question, there was first argument of type object, and generic method was
DoSomething<object,Type>(object o, Type t)
And again, parameter sequences are equivalent in this case, and non-generic method is picked.
In my test, I was able to use a cast to get the resolution you want. DoSomething((object)"1234", typeof(string));
Call
DoSomething<object, SomeType>(obj, type)();

What are the rules of precedence in resolving the method overloading in C#?

I'm writing a serializer in which I want to make use of method overloads extensively, to serialize objects of types deriving from IEnumerable<T>, IDictionary<K,V> and so on.
I also intend to use dynamic keyword to let CLR choose the correct overload based on the runtime type of the object to be serialized.
Have a look at this code snippet:
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 runtime-type of obj, the correct overload will be called. For example,
//Test code
CallSerialize(new List<int>()); //prints IEnumerable<T>
In this case, the third overload is called and the rationale is pretty much straightforward : that is only the viable option.
However, if I do this:
CallSerialize(new Dictionary<int,int>()); //prints IDictionary<TKey, TValue>
It calls the first overload. I don't exactly understand this. Why does it resolve to the first overload when all three overloads are viable options?
In fact, if I remove the first one, the second overload is called, and if I remove the first and second overload, then the third overload is called.
What are the rules of precedence in resolving the method overloading?
The rules for resolving method overloads will try to pick the method header with the most specific type match. Here you can read more about overload resolution and here I think is your case.
From MSDN:
Given an argument list A with a set of argument types {A1, A2, ..., AN} and two applicable function members MP and MQ with parameter types {P1, P2, ..., PN} and {Q1, Q2, ..., QN}, MP is defined to be a better function member than MQ if
for each argument, the implicit conversion from AX to PX is not worse than the implicit conversion from AX to QX, and
for at least one argument, the conversion from AX to PX is better than the conversion from >AX to QX.
When performing this evaluation, if MP or MQ is applicable in its expanded form, then PX or QX refers to a parameter in the expanded form of the parameter list.

Categories