c# - Why Visual Studio is using EqualityComparer when auto-generating Equals? -
i using visual studio community 2017. when create class, in quick actions menu, can choose "generate equals(object)".
let's have account class:
class account { public ushort? id { get; private set; } public string comments { get; private set; } public list<contact> contacts { get; private set; } public string label { get; private set; } public lawyer lawyer { get; private set; } } the generated methods are:
public override bool equals(object obj) { return equals(obj account); } public bool equals(account other) { return other != null && equalitycomparer<ushort?>.default.equals(id, other.id) && comments == other.comments && equalitycomparer<list<contact>>.default.equals(contacts, other.contacts) && label == other.label && equalitycomparer<lawyer>.default.equals(lawyer, other.lawyer); } for comments , label visual studio uses ==, while id, list , lawyer uses equalitycomparer.
my first thought == used value types while equalitycomparer used reference types. problem string not value type (although used 1 in equality context) , ushort? not reference type.
my second thought because ushort?, list , lawyer accept null. problem string accepts null well.
so rule? when chooses equalitycomparer , when uses simple ==? why?
type nullable<t> not have operator ==, not implement iequatable<t> interface , has object.equals(object other) method. direct calling of object.equals value types unwanted.
therefore, equalitycomparer<ushort?>.default.equals used. implemented as:
internal class nullableequalitycomparer<t> : equalitycomparer<nullable<t>> t : struct, iequatable<t> { public override bool equals(nullable<t> x, nullable<t> y) { if (x.hasvalue) { if (y.hasvalue) return x.value.equals(y.value); return false; } if (y.hasvalue) return false; return true; }
Comments
Post a Comment