user
user

Reputation: 246

C#.NET check if the object is null or not

Am I doing this correct? I'm interested to know the possible reasons why its failing?

Object obj = Find(id); //returns the object. if not found, returns null
if (!Object.ReferenceEquals(obj, null))
{
     //do stuff
}
else
{
     //do stuff
}

Find Method (Uses ORM Dapper). Performed unit tests on this, I believe there is no problem with this method.

public Object Find(string id)
{
     var result = this.db.QueryMultiple("GetDetails", new { Id = id }, commandType: CommandType.StoredProcedure);
     var obj = result.Read<Object>().SingleOrDefault();
     return obj;
}

Upvotes: 4

Views: 53947

Answers (2)

Adarsh Shah
Adarsh Shah

Reputation: 6775

I would do following. Why negate the null check unnecessarily?

Object obj = Find(id); //returns the object. if not found, returns null

if (obj == null)
{
        //do stuff when obj is null
}
else
{
        //do stuff when obj is not null
}

Upvotes: 0

ekad
ekad

Reputation: 14624

Try this:

   Object obj = Find(id); //returns the object. if not found, returns null
   if (obj != null)
   {
        //do stuff when obj is not null
   }
   else
   {
        //do stuff when obj is null
   }

Upvotes: 18

Related Questions