Is it possible to call a method on a null object reference? Of course, not!
static void Main( string[] args )
{
Foo _foo = null;
// will throw NullReferenceException
Console.WriteLine( _foo.Bar() );
Console.ReadLine();
}
Oh, really?
Your goal is to provide all necessary auxiliary definitions and implementations so that the code above not only does not throw NullReferenceException but also writes “Hello world” at the console.
My solution using extension method:
ReplyDeletepublic class Foo {}
public static class FooExtension
{
public static string Bar(this Foo foo)
{
return "Hello world";
}
}
class Program
{
static void Main(string[] args)
{
Foo _foo = null;
Console.WriteLine(_foo.Bar());
Console.ReadLine();
}
}
That's exactly what I've been thinking of. Regards :)
ReplyDelete