Tuesday, June 12, 2007

C# quiz #2: objects, strings, null

this is a continuation from the previous quiz; given this class definition:

public class Foo {
    public void Bar(object x) {
        Console.WriteLine("object x was called");
    }
    public void Bar(string x) {
        Console.WriteLine("string x was called");
    }
}

what will be output to the console with the following code:

Foo f = new Foo();
try {
    f.Bar(null);
}
catch {
    Console.WriteLine("no method was called");
}

Extra points for explaining why

2 comments:

Anonymous said...

Hmmm.... this puzzles me. This time my first hunch was actually wrong. This code compiles.
I've read the C# language specification to find out what is going on here. I suppose it has something to do with the 'Better conversion' (7.4.2.3) section of the specs, but I can't figure it out. It seems to me that neither conversion (null to object and null to string) is better, so a compile time error should be generated.

I suppose I misread the specs.

Bubba said...

Can u post the explanation?