A ChallangeImplement This...

time to read 9 min | 1780 words

How would you write the following code so it would print "Bar" to the screen:

Foo foo = new Foo();

foo.DoWork("Foo");

foo.DoWork("Bar");

Can you make it work? You may not use any conditional operations.

Hint: Think Dynamically...

Update: To clarify, you should provide the rest of the code so those three lines will output "Bar" to the screen. You can implement Foo() anyway you want, and you can put more code between DoWork("Foo") and DoWork("Bar"), but you can't use conditinal operation (if, while, etc...).

Update II: Oren Ellenbogen suggested a solution like this:

static void Main (string[] args)

{

    using (Foo1 foo1 = new Foo1())

    {

        foo1.DoWork("Foo");

        foo1.DoWork("Bar");

    }

}

class Foo1 : IDisposable

{

    string last;

 

    public void DoWork(string arg)

    {

        this.last = arg;

    }

 

    public void Dispose()

    {

        Console.WriteLine(last);

    }

}

This answers the conditions of the the original challange, but it wasn't what I had in mind. So now you need to profuce "Bar", "Fubar" from this code, without using conditinals or loops.

Foo foo = new Foo();

foo.DoWork("Foo");

foo.DoWork("Bar");

foo.DoWork("Fubar");

Thinking about it, I realize that there are actually several other ways to do it than the one I thought of, most of them are not obvious, so I'll let the challange stand for now.

Another hint: I'm looking for another "What the F%$@ was he thinking..."

More posts in "A Challange" series:

  1. (24 Dec 2006) Simple HR Model + Rules
  2. (18 May 2006) Implement This...