Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer NULL to the constructor

I can not understand why the constructor is executed with the parameter Double[]?

using System.Collections.Generic; using System.Linq; using System.Text;  namespace MyConsoleApp {     class Program     {         static void Main(string[] args)         {             D myD = new D(null);             Console.ReadLine();                    }      }      public class D     {         public D(object o)         {             Console.WriteLine("Object");         }         public D(double[] array)         {             Console.WriteLine("Array");         }         public D(int i)         {             Console.WriteLine("Int");         }     } } 

I think because the first constructor takes a parameter of reference type. The first constructor with a reference parameter because null is the default value for reference types.

But i don't understand why not object, it's also a reference type.

like image 565
Dima Kozyr Avatar asked Feb 09 '14 20:02

Dima Kozyr


Video Answer


2 Answers

But I can not understand why no object? It's also a reference type?

Yes, both double[] and object are reference types, so null is implicitly convertible to both of them. However, member overloading generally favours more specific types, so the double[] constructor is used. See section 7.5.3 of the C# specification for more details (and boy are there a lot of details).

In particular, from section 7.5.3.5:

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

That's the case here, where T1 is double[] and T2 is object. There's an implicit conversion from double[] to object, but no implicit conversion from object to double[], so double[] is a better conversion target than object.

If you want force the use of the object constructor, just cast:

D myD = new D((object) null); 
like image 59
Jon Skeet Avatar answered Sep 29 '22 07:09

Jon Skeet


Basically, double[] is an object, but all objects are not double[]s. As double[]'s the more specific option, the compiler chooses it, as the most specific one.

like image 42
It'sNotALie. Avatar answered Sep 29 '22 07:09

It'sNotALie.