Why second constructor is called??

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");
}

}
}
 
M

Marc Gravell

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
 
J

Jon Skeet [C# MVP]

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
 
C

Chris Shepherd

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top