0

If I check the equalities of two datas with first if statement when ent.column is empty there will be error:

Object reference not set to an instance of an object.

When I check the equalities of two datas with second if statement and args.column is null, everything is works fine. Sorry for bad explain, this one is my first on stackoverflow.

myTable ent;//this comes from db;
myclass args// this comes from view;

//gives error
if(ent.column.Equals(args.column)){
  //some code         
}

//successfully check 
if(args.column.Equals(ent.column)){ 
  //some code         
}
Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
aslandgn
  • 11
  • 3
  • 5
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Diado Oct 12 '18 at 13:16
  • Welcome to StackOverflow. Please take some time to read through the [Help Center](https://stackoverflow.com/help) and in particular [How do I ask a good question](https://stackoverflow.com/help/how-to-ask). – Chris Pickford Oct 12 '18 at 13:24
  • 1
    _"When I check the equalities of two datas with second if statement and args.column is null, everything is works fine."_ Then you are looking wrong. You cannot call `Equals` on `null`. If this is a typo and you meant that in the second if it works if **ent** .column is null then that would be expected. Because you can check equality with `null`. – Fildor Oct 12 '18 at 13:24
  • In your first if statement is ent null or is column null? If ent is null you'll get a null reference exception from trying to access column. If column is null, you'll get a null reference exception from tryin gto call `Equals` on it – Bruno Oct 12 '18 at 13:28

1 Answers1

0

Basically:

myObject.NonNullProperty.Equals(null); // works ...

... because a) I can call Equals on that property (which is not null) and b) Equals accepts null without throwing an exception.

myObject.NullProperty.Equals(anotherObject); // fails ...

... because (given NullProperty is null) you cannot call an instance method (here: "Equals") if there is no instance of any object.

Possible workaround:

if( myObject.MayBeNullProp != null && // stops evaluating here if false
    theOtherObject.MayBeNullProp != null && // stops evaluating here if false
    myObject.MayBeNullProp.Equals(theOtherObject.MayBeNullProp) ) 
{
   // Executed if both are != null and equal
}
Fildor
  • 14,510
  • 4
  • 35
  • 67