-5

I have an object array as follows:

private object[] _yazdirmaBilgisi = new object[5];

On some point I want to access the first element but of course I wanna check if it is null first

At some point [0] is null but [1] is not null.

When I check if the value is null with Equals it throws exception:

if (!_yazdirmaBilgisi[0].Equals(null))  //Throws exception

But if i check with != null ne exception

if (_yazdirmaBilgisi[0] != null) // No exception

Why does it differ? Why Equals(null) throws exception but != null doesn't

dkozl
  • 31,864
  • 8
  • 85
  • 87
icemalkan
  • 61
  • 1
  • 6

3 Answers3

3

Because == null isn't the same as .Equals(null). If you use Equals, you will obviously get an exception because of trying to access null reference. == works different, similar to Object.Equals(a,b) in that it checks if both values are null first, then it does more comparing.

IS4
  • 10,514
  • 2
  • 45
  • 74
1

The first throws because the first element in the list is a null reference. This is what your code is doing:

var element = _yazdirmaBilgisi[0];
if (element.Equals(null)) // element is null, and null.Equals is calling a method on a null reference

The == operator is defined to do something similar to this:

var element = _yazdirmaBilgisi[0]; // element is reference who's value is null
if (object.ReferenceEquals(element, null)) // object.Equals is a static method which doesn't require an object instance
Andy
  • 8,287
  • 5
  • 37
  • 73
  • 4
    *The == operator is overloaded to do this* is misleading. – Sriram Sakthivel Nov 13 '14 at 14:54
  • @SriramSakthivel I removed the term overload, but otherwise how is it misleading? – Andy Nov 13 '14 at 23:15
  • Now that's fine. Not only the term *overloaded* was misleading, you said it is overloaded to do `object.Equals`, that's wrong. Later you changed it to `ReferenceEquals`. – Sriram Sakthivel Nov 14 '14 at 06:39
  • @SriramSakthivel I'm not sure I like ReferenceEquals either (which is why I said my code is similar). In the question he's explicitly using System.Objects, but Strings do define the == operator and it'd be a bit more complicated than my sample. – Andy Nov 14 '14 at 14:58
1

This line:

if (!_yazdirmaBilgisi[0].Equals(null)) 
  1. Extracts a reference from _yazdirmaBilgisi[0]
  2. Uses that reference as the object on which to call .Equals().

But because that reference is null, it throws a NullReferenceException.

Whereas:

if (_yazdirmaBilgisi[0] != null)

is directly comparing the reference in _yazdirmaBilgisi[0] with null, so it doesn't throw an exception - it is not trying to call any methods of the referenced object.

Matthew Watson
  • 96,889
  • 9
  • 144
  • 240