C# Brainteasers

Every so often I run into an interesting situation in C# which gives surprising results. This page contains a collection of examples. When only a snippet is given, assume that it exists in a Main method and just runs. To save accidentally seeing the result before you want to, I've put the answers on a separate page.

1) Overloading

What is displayed, and why?

using System;

class Base
{
    public virtual void Foo(int x)
    {
        Console.WriteLine ("Base.Foo(int)");
    }
}

class Derived : Base
{
    public override void Foo(int x)
    {
        Console.WriteLine ("Derived.Foo(int)");
    }
    
    public void Foo(object o)
    {
        Console.WriteLine ("Derived.Foo(object)");
    }
}

class Test
{
    static void Main()
    {
        Derived d = new Derived();
        int i = 10;
        d.Foo(i);
    }
}

2) Order! Order!

What will be displayed, why, and how confident are you?

using System;

class Foo
{
    static Foo()
    {
        Console.WriteLine ("Foo");
    }
}

class Bar
{
    static int i = Init();
    
    static int Init()
    {
        Console.WriteLine("Bar");
        return 0;
    }
}

class Test
{
    static void Main()
    {
        Foo f = new Foo();
        Bar b = new Bar();
    }
}

3) Silly arithmetic

Computers are meant to be good at arithmetic, aren't they? Why does this print "False"?

double d1 = 1.000001;
double d2 = 0.000001;
Console.WriteLine((d1-d2)==1.0);

4) Print, print, print...

Here's some code using the anonymous method feature of C# 2. What does it do?

using System;
using System.Collections.Generic;

class Test
{
    delegate void Printer();
    
    static void Main()
    {
        List<Printer> printers = new List<Printer>();
        for (int i=0; i < 10; i++)
        {
            printers.Add(delegate { Console.WriteLine(i); });
        }
        
        foreach (Printer printer in printers)
        {
            printer();
        }
    }
}

5) Literally nothing wrong with the compiler here...

Should this code compile? Does it? What does it mean?

using System;

class Test
{
    enum Foo { Bar, Baz };
    
    static void Main()
    {
        Foo f = 0.0;
        Console.WriteLine(f);
    }
}

More along the same lines...

using System;

class Test
{
    enum Foo { Bar, Baz };
    
    const int One = 1;
    const int Une = 1;
    
    static void Main()
    {
        Foo f = One-Une;
        Console.WriteLine(f);
    }
}

6) Type inference a-go-go

I first saw this on Ayende's blog (in a rather more obscure form, admittedly). Once again, work out what will be printed, and why.

using System;

class Test
{
    static void Main()
    {
        Foo("Hello");
    }
    
    static void Foo(object x)
    {
        Console.WriteLine("object");
    }
    
    static void Foo<T>(params T[] x)
    {
        Console.WriteLine("params T[]");
    }
}



Back to the main page.