Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null dynamic variable and function overloading

Tags:

c#

.net

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).

like image 516
Moe Sisko Avatar asked May 07 '15 05:05

Moe Sisko


2 Answers

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 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.

And later on the better conversion target gets defined:

7.5.3.5 Better conversion target

Given two different types T1 and T2, T1 is a better conversion target than T2 if at least one of the following holds:

  • An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists

(...)

In your example T1 is object[] and T2 is object.

like image 172
MarcinJuraszek Avatar answered Nov 08 '22 00:11

MarcinJuraszek


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.

like image 7
imlokesh Avatar answered Nov 08 '22 01:11

imlokesh