0

Possible Duplicate:
Is there a reason why NullReferenceException does not give the name of the variable?

Why Even higher level languages like C# or Java couldnt easily provide a mechanism to find which object type and instance (variable) is null? Should we need to write a custom logic for the same.

 ex:   SampleClass sc = null;
       sc.SomeMethod();

I would like to say "Object sc of type SampleClass is null" rather than a naive exception message "Object reference not set to an instance of an object."

Community
  • 1
  • 1
NSN
  • 740
  • 3
  • 9
  • 26
  • possible duplicate of [Is there a reason why NullReferenceException does not give the name of the variable?](http://stackoverflow.com/questions/5257626/is-there-a-reason-why-nullreferenceexception-does-not-give-the-name-of-the-varia), also [Why doesn't NullReferenceException contain information about what is null?](http://stackoverflow.com/questions/4719047/why-doesnt-nullreferenceexception-contain-information-about-what-is-null) – Rawling Nov 29 '12 at 12:01

2 Answers2

2

It's worth being clear on terminology here. sc isn't an object, it's a variable. The value of the variable is a reference. The reference may be null, or it may be a reference to a real object.

Now, as for why it's not as simple as it sounds...

In this code:

sc.SomeMethod();

... there are two operations:

  • Load value of sc onto the execution stack
  • Execute SomeMethod via the reference on the execution stack

It's the second operation which fails, and that operation doesn't "know" about the first operation, really.

It becomes worse when there are more operations involved. What about:

Foo().Bar().SomeMethod()

What would you expect the exception to show in this case?

Personally I rarely find it that hard to work out where the exception is coming from - the line number normally makes it fairly clear, and the situations in which it's not clear are usually precisely the situations where there's a long expression which couldn't easily give a single answer in the exception anyway.

I guess it would be possible for the CLR/compiler to agree on an extra table, like the line number mapping, which says "for IL instruction X, the top of the execution stack was from an expression with diagnostic message Y". It feels like it would be pretty cumbersome though - and as I say, it shouldn't really give you that much of a headache.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Because in most cases it is not that simple.

Take this method for example:

public int Foo(string bar)
{
    return bar.Length;
}

bar could be null depending on factors only known at runtime. That's nothing the compiler can ever verify.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443