0

Doing refactoring, I changed a variable name in expression to "this", and it made the expression this?.RaiseEvent(eventArg). And not only it compiled well, it didn't show me any warnings. So I am confused a little bit - is there any cases when this can be null in C#? If not, what is the reason for such a behavior of compiler?

svick
  • 236,525
  • 50
  • 385
  • 514
Alex Butenko
  • 3,664
  • 3
  • 35
  • 54
  • 5
    Why add a special case just for `this`? – i3arnon Feb 14 '16 at 01:30
  • C# compiler tracks unused variables and many other things as warnings, so I would expect the same for obviously useless expressions like this one. – Alex Butenko Feb 14 '16 at 01:35
  • 5
    Looks like here is the answer [this-null-inside-net-instance-method](http://stackoverflow.com/questions/10625326/this-null-inside-net-instance-method-why-is-that-possible) – Mike Znaet Feb 14 '16 at 04:47
  • @MikeZnaet Wow, It's something I didn't know! It explains everything. If you'll make it an answer, I will certainly accept it. – Alex Butenko Feb 14 '16 at 08:13
  • That's a problem caused by "malicious" use of reflection. It's not a condition that you would run into under normal circumstances. One could argue that they could have added checks there but those are pretty low level methods so that should be done by the programmer, not the API. – Jeff Mercado Feb 15 '16 at 05:39
  • @JeffMercado, not necessarily malicious at all. C# refuses to call a method on a null instance, but it isn't a .NET rule that languages have to. – Jon Hanna Feb 24 '16 at 13:51
  • Possible duplicate of [this == null inside .NET instance method - why is that possible?](https://stackoverflow.com/questions/10625326/this-null-inside-net-instance-method-why-is-that-possible) – Alex Butenko Feb 05 '18 at 14:44

0 Answers0