Example code :
private void DoSomething(object obj)
{
MessageBox.Show("called object");
}
private void DoSomething(params object[] obj)
{
MessageBox.Show("called object[]");
}
private void button1_Click(object sender, EventArgs e)
{
decimal? amount = null;
dynamic obj = amount;
DoSomething(obj);
}
When button 1 is clicked, the message "called object[]" is displayed. It seems that the overloaded method with object[] parameter is preferred in this example. Any ideas why ? I'm just curious more than anything.
(Background : this behavior caused some unexpected results in Razor with dynamic views Formatting nullable decimal in RazorEngine).
That's because you can cast object[]
to object
and not the other way around. object[]
is more specific and therefore favored in method resolution.
7.5.3.2 Better function member
(...)
Given an argument list A with a set of argument expressions
{ E1, E2, ..., EN }
and two applicable function membersMP
andMQ
with parameter types{ P1, P2, ..., PN }
and{ Q1, Q2, ..., QN }
,MP
is defined to be a better function member thanMQ
if
- for each argument, the implicit conversion from
EX
toQX
is not better than the implicit conversion fromEX
toPX
, and- for at least one argument, the conversion from
EX
toPX
is better than the conversion fromEX
toQX
.
And later on the better conversion target gets defined:
7.5.3.5 Better conversion target
Given two different types
T1
andT2
,T1
is a better conversion target thanT2
if at least one of the following holds:
- An implicit conversion from
T1
toT2
exists, and no implicit conversion fromT2
toT1
exists(...)
In your example T1
is object[]
and T2
is object
.
The problem is not specific to "null dynamic variable". Even if you call DoSomething(null)
, the object[]
overload will be preferred.
This is because even though null can be either object
or object[]
, the latter is preferred due to it being a Better Conversion Target as explained by MarcinJuraszek.
However, if you specify the type explicitly like this:
object x = null;
DoSomething(x);
Then the object
overload will be called since the compiler already knows the type of the null variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With