11
Voxera
5y

I don’t know if I would call it a quirk of the language or serious abuse of it :P

But I managed to get a null ref exception when comparing a local int variable to an int parameter to the same function in C#.

Since a local or parameter of type in cannot be null and I compared the variables them self and dud not try to access any property on them (and no extension method or implicit case or similar) my first thought, along with all colleagues that chipped in to help, was that this should not be possible.

Turns out the method was called through reflection and in that part it injected null as the base object to call the method on.

Since local variables actually are referenced through the parent object this was what was causing the null ref.

That took some time to figure out.

Comments
  • 1
    Definitely why I make most types nullable anymore. Seen this happen with flubbed emit namespace operations as well.
  • 3
    @SortOfTested in this case it would mot have helped.

    The actual statement causing this was

    public MyClass DoIt(int a) {

    if(a > 0)
    {
    ...

    And a caused null reference error :)

    Not what you would expect.

    But with reflection, you can really break things :D
  • 2
    interesting! 😄
    I like errors which look impossible at first, because they always tell a story.
  • 0
    This is one for the grand kids
Add Comment