Tuesday, January 6, 2009

C# Puzzles

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?

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 printers = new List();
        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

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(params T[] x)
    {
        Console.WriteLine("params T[]");
    }
}

Based on http://www.yoda.arachsys.com/csharp/teasers.html

No comments:

Post a Comment