Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading and null value [duplicate]

Tags:

c#

Possible Duplicate:
C#: Passing null to overloaded method - which method is called?

Consider these 2 methods:

void Method(object obj)  { Console.WriteLine("object"); }
void Method(int[] array) { Console.WriteLine("int[]"); }

When I try calling:

Method(null);

in Visual Studio 2008 SP1 I get int[].

Why is this?

like image 841
Pritorian Avatar asked Nov 22 '11 15:11

Pritorian


2 Answers

It is a product of overload resolution. Your argument, null, is convertible to both object and int[]. The compiler therefore picks the most specific version, because int[] is more specific than object.

like image 113
Anthony Pegram Avatar answered Nov 14 '22 21:11

Anthony Pegram


Because int[] is more specific than object, the method with the object-parameter will be ignored. If you would call Method("Some string"), the method with the object-parameter will be called.

like image 25
Abbas Avatar answered Nov 14 '22 20:11

Abbas