Move NULL to constructor

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

 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 accepts a reference type parameter. 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 is also a reference type.

+60
constructor c # overloading constructor-overloading
Feb 09 '14 at 20:50
source share
3 answers

But I do not understand why there is no object? Is it also a reference type?

Yes, both double[] and object are reference types, so null implicitly converted to both of them. However, overloading elements usually favors more specific types, so the double[] constructor is used. See Section 7.5.3 of the C # Specification for details (and the boy has many details).

In particular, from section 7.5.3.5:

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

  • There is an implicit conversion from T1 to T2, and there is no implicit conversion from T2 to T1.

In this case, here T1 double[] and T2 is object . There is an implicit conversion from double[] to object , but an implicit conversion from object to double[] , so double[] is a better conversion goal than object .

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

 D myD = new D((object) null); 
+90
Feb 09 '14 at 20:52
source share

Basically, double[] is an object , but all object not double[] s. Since double[] more specific option, the compiler selects it as the most specific.

+19
Feb 09 '14 at 20:54
source share

Consider this:

 double[] d = new double[] {}; Console.WriteLine(d is object);//output is True 

double [] d is the object.

So, consider the following:

 object z = new object[] {}; Console.WriteLine(z is double[]);//output is False 

object [] z is not double []. There is no implicit conversion from an object to double [].

+2
Feb 10 '14 at 4:22
source share



All Articles