I hope this is appropriate for this site because I already figured out the answer, so it’s more a quiz than a question.
This C# code works with no problem:
WidgetRef = widget as IWidget;
WidgetRef.Init();
However if I try changing it to:
WidgetRef = (IWidget)widget;
WidgetRef.Init();
in some situations I get a “cannot cast to IWidget” exception.
At first I was dumfounded how that could be possible, because if it can’t cast in the 2nd example, it should throw a null exception in the 1st example. But I discovered it ain’t necessarily so 🙂
How is this possible?
OK, here’s the answer….
The incorrect assumption that I was making as that
WidgetRefwas a variable or field. It was actually a property, defined like this:where
NullWidgetis a class implementingIWidgetin a minimal way. So even thoughnullwas being assigned in toWidgetRef, that wasn’t what was coming out of it!