c# - When to specify constraint `T : IEquatable<T>` even though it is not strictly required? -
in short, looking guidance on of following 2 methods should preferred (and why):
static ienumerable<t> distincta<t>(this ienumerable<t> xs) { return new hashset<t>(xs); } static ienumerable<t> distinctb<t>(this ienumerable<t> xs) t : iequatable<t> { return new hashset<t>(xs); }
argument in favour of
distincta
: obviously, constraint ont
not required, becausehashset<t>
not require it, , because instances oft
guaranteed convertiblesystem.object
, provides same functionalityiequatable<t>
(namely 2 methodsequals
,gethashcode
). (while non-generic methods cause boxing value types, that's not i'm concerned here.)argument in favour of
distinctb
: generic parameter constraint, while not strictly necessary, makes visible callers method compare instances oft
, , therefore signalequals
,gethashcode
should work correctlyt
. (after all, defining new type without explicitly implementingequals
,gethashcode
happens easily, constraint might catch errors early.)
question: there established , documented best practice recommends when specify particular constraint (t : iequatable<t>
), , when not to? , if not, 1 of above arguments flawed in way? (in case, i'd prefer well-thought-out arguments, not personal opinions.)
start considering when might matter of 2 mechanisms used; can think of two:
- when code being translated language (either subsequent version of c#, or related language java, or completly dissimilar language such haskell). in case second definition better providing translator, whether automated or manual, more information.
- when user unfamiliar code reading learn how invoke method. again, believe second better providing more information readily such user.
i cannot think of circumstance in fist definition preferred, , matters beyond personal preference.
others thoughts?
Comments
Post a Comment