Small challenge: call method on null

Inspired by some talk I "overheard" on twitter I thought it would be interesting to post a small challenge. Is it possible to implement the missing parts of the following code so it compiles and runs without exceptions, if yes how would you do it? You are not allowed to modify the body of the Main method but the rest is up to you.

static void Main(string[] args)
{
    Foo f = null;
    f.Bar();
}

And yes its a pretty useless exercise :-)


Comments

April 25. 2008 07:44 AM

Henrik W H

3 minutes Smile
This will compile:
--
namespace ConsoleApplication2
{
public delegate void Foo();
public static class MyExtensions
{
public static void Bar(this Foo i) { }
}
class Program
{
static void Main(string[] args)
{
Foo f = null;
f.Bar();
}
}
}
--
Not sure if thats what your after.
/Henrik

Henrik W H

April 25. 2008 08:08 AM

Jakob Andersen

Thats it, and im pretty sure it cannot be done in any other way. How pointless it may be to achieve this it makes it pretty obvious that extension methods is just syntactic sugar Smile

Jakob Andersen

Comments are closed