With C# 6.0 I can do this
var isEqual = x.Id == y.Id
&& x.UpdatedAt == y.UpdatedAt
&& x.Name == y.Name
&& x.RulesUrl == y.RulesUrl
&& x.OngoingChallenges?.Count == y.OngoingChallenges?.Count
&& x.MembershipIds?.Count == y.MembershipIds?.Count;
Is there any nice solution to do this with C# < 6.0?
I mean this part
&& x.OngoingChallenges?.Count == y.OngoingChallenges?.Count
&& x.MembershipIds?.Count == y.MembershipIds?.Count;
Because in old projects we do not have possibility to use C# 6.0. How to write isEqual
efficiently?
Before C# 6, i used something like this
x.OnGoingChallenges?.Count
is equivalent tox.OnGoingChallenges != null ? x.OnGoingChallenges.Count : default(int?)
(there're other approaches, but at the end of the day is a shortcut to null checking called null-conditional operator).That is, your code can't be rewritten with a syntatically elegant statement without C# 6, but you can emulate this new C# 6 feature using extension methods...
And now your code in C#5 would look as follows:
The whole extension method would work for getting a value-typed property value or its default value. You might or might not extend the extension method class to also support getting a reference type value or null.
In C# version < 6.0 you would use ternary expressions
As @Hamlet Hakobyan has pointed out, this not the semantically exact equivalent of the original C# 6.0 solution using
?.
, but you could change it to (according to @hvd):It depends whether you want to consider a missing collection and an empty collection as equal or not.
You could also use the null-coalescing operator
??
and provide a replacement object. Assuming that your objects are lists of some kind: