Showing posts with label Teasers. Show all posts
Showing posts with label Teasers. Show all posts

C# Brainteaser 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();
}
}
}




Answer: Ah, the joys of captured variables. There's only one i variable here, and its value changes on each iteration of the loop. The anonymous methods capture the variable itself rather than its value at the point of creation - so the result is 10 printed ten times!

C# Brainteaser 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);






Answer: All the values here are stored as binary floating point. While 1.0 can be stored exactly, 1.000001 is actually stored as 1.0000009999999999177333620536956004798412322998046875, and 0.000001 is actually stored as 0.000000999999999999999954748111825886258685613938723690807819366455078125. The difference between them isn't exactly 1.0, and in fact the difference can't be stored exactly either

C# Brainteaser Order it

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




Answer: On my box, Bar is printed and then Foo. This is because Foo has a static constructor, which cannot be run until the exact point at which the class first has to be initialized. Bar doesn't have a static constructor though, so the CLR is allowed to initialize it earlier. However, there's nothing to guarantee that Bar will be printed at all. No static fields have been referenced, so in theory the CLR doesn't have to initialize it at all in our example.

C# Brainteaser 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);
}
}


Answer: Derived.Foo(object) is printed - when choosing an overload, if there are any compatible methods declared in a derived class, all signatures declared in the base class are ignored - even if they're overridden in the same derived class!