Why second constructor is called??

  • Thread starter Thread starter anoj
  • Start date Start date
A

anoj

Why the constructor with String parameter gets called whenever value
of null is passed (see below)??

===============

using System;
using System.Collections.Generic;

namespace simple
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
X objx=new X(null);
}
}

class X
{
public X(Object a)
{
Console.Write("Object.A");
}

public X(String a)
{
Console.Write("String.A");
}

}
}
 
It is a bit ambiguous, isn't it...

At a /guess/, it concludes that "string" is more specific than
"object", since both "fit", and string : object... but a warning would
be nice I suppose...

Marc
 
Why the constructor with String parameter gets called whenever value
of null is passed (see below)??

null is convertible to both String and Object, so the compiler follows
the rules as to which is the "better" conversion - as String is more
specific than Object, it uses that one.

If you want to call the object one, just cast the null to object.

Jon
 
anoj said:
Why the constructor with String parameter gets called whenever value
of null is passed (see below)??

Probably because string is more specific than object.
You can indicate which constructor to call by doing:

X objx=new X(null as Object);



Chris.
 
Back
Top