I have .NET application that crashes with NullReferenceException. The funny thing is that the log shows this:
Inner Exception System.NullReferenceException: Object reference not set to an instance of an object.
at System.Object.GetType()
The thing that’s puzzling me is that the exception happens inside of GetType instead on the line that calls GetType. I’ve tested following situations.
If I call GetType on an object that is null, the exception happens on a line that’s calling GetType, not within GetType.
I also tried How can I get a NullReferenceException in this code sample? but strangely
I get the exception in Program.Main not within Object.GetType (although in that post it’s within GetType).
I also tried concurrently creating objects and calling GetType, but needlesly to say,
there is no window in creation of .net objects where GetType throws NullReferenceException.
The only thing that crosses my mind right now is that this was maybe behavior of some older .NET implementation.
So any idea how to cause NullReferenceException within GetType, and if you could provide proof of concept code I would be eternally grateful.
Thank you for your time.
One way would be to call the
GetTypemethod (“on” anull-reference) with thecallinstruction rather than the with thecallvirtinstruction that C# normally uses. This will prevent the pre-method-call runtime null-check from occurring. Instead, the null-reference would be passed to the method, causing the exception to be thrown inside the method itself.For example, using the
InvokeNonVirtualsample provided here, you can do:This produces a
TargetInvocationExceptionwith theInnerExceptionbeing aNullReferenceExceptionhaving stack-trace: