Thursday, April 23, 2009

Puzzle

Consider the following:
I provide you with a .net 3.5 dll that implements the class SomeClass plus some operations that operate on this class. The Isvalid method has no side effects, will throw no exception and always return true.

You run the following code:
What is output to the screen?
  1. "o is valid"
  2. "o is not valid"
  3. "Exception has been thrown"
  4. impossible to predict
Place your bets please

3 comments:

  1. The Answer:

    The answer i 4. There is no way to tell what the output is.

    The reason for this is that on line 13 where the IsValid method 'o' will bee null.
    If the Isvalid is implemented as a standard instance method on the SomeClass type a NullPointerException will be thrown.
    If on the other hand IsValid is implemented as an extension method a IsValid will execute and return true.

    As I didn't tell you if IsValid was an extension method or an instance method there is no way you can predict which is written to the screen.

    ReplyDelete
  2. One could argue intelliSense would have shown us which was the case, if you actually provided the dll you talk about ;-)

    ReplyDelete
  3. I could have just given you the answer to begin with :)

    ReplyDelete