user1679941
user1679941

Reputation:

Is there a .Equals function in C# that takes into account nulls?

I have this code:

var upd = newObj.Where(n => oldObj.Any(o =>
  (o.SubTopicId == n.SubTopicId) && 
  (o.Number != n.Number ||
   !o.Name.Equals(n.Name) || 
   !o.Notes.Equals(n.Notes))))
.ToList();

What I noticed is that when Notes is null then the .Equals fails.

.","exceptionMessage":"Object reference not set to an instance of an object.","exceptionType":"System.NullReferenceException","stackTrace":" at WebRole.Controllers.TopicController.<>c__DisplayClass8_1.b__1(SubTopic o) in C:\H\server\WebRole\Controllers\Web API - Data\TopicController.cs:line 118\r\n at System

Is there some way that I could the .Equals take into account that either o.Notes or n.Notes could actually be null? Ideally I am wondering if I could have another function as I do this kind of check in quite a few places in my code.

Upvotes: 1

Views: 78

Answers (2)

Charles Mager
Charles Mager

Reputation: 26213

You could use the static object.Equals(object objA, object objB) method.

Given everything derives from object, you can omit the object and simply call Equals, e.g:

 oldObj.Any(o => !Equals(o.Name, n.Name) ...

This handles the case where either of the arguments is null by returning false and returns true where both arguments are null.

Per the docs:

  • It determines whether the two objects represent the same object reference. If they do, the method returns true. This test is equivalent to calling the ReferenceEquals method. In addition, if both objA and objB are null, the method returns true.
  • It determines whether either objA or objB is null. If so, it returns false.
  • If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. This means that if objA overrides the Object.Equals(Object) method, this override is called.

Upvotes: 4

Robin
Robin

Reputation: 47

You could use the static object.Equals(object objA, object objB) method (docs). This method handles the case where either argument is null before potentially calling objA.Equals(objB).

Upvotes: 0

Related Questions