Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did this compile?

The code below compiled without a problem. It's clear _dependency will always be null, so it's not possible to use it in any way (aside from evaluating it) - is it? Why was the compiler not aware of this and fail it?

public class MyClass
{
   private readonly MyDependency _dependency;

   public MyClass()
   {
      _dependency.MyMethod();
   }
}

To be clear, I know the code above is bad code, and it is the developers fault - but as is any other compile-time error. I would've thought the compiler would've thrown a use of unassigned variable kind of error.

Why did this compile? Am I unaware of a scenario whereby it would be fine to use a null object like this?

EDIT:

To confirm - I am not wishing to rely on the compiler to check for poorly written code - and I appreciate that, syntactically, it is absolutely fine. My question really is two-fold, is there a scenario which I'm unaware of which may make this code execute fine. And the second question is - why wouldn't it detect such an issue, if it already deals with use of unassigned variable errors? What's the difference?


1 Answers

Because the compiler doesn't check for that kind of issues. It's syntactically correct, and perfectly fine. Null reference issues are usually only detected on runtime, unless you use code analysis tools that will detect that kind of issues.

like image 113
Gimly Avatar answered Mar 03 '26 16:03

Gimly