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 on t not required, because hashset<t> not require it, , because instances of t guaranteed convertible system.object, provides same functionality iequatable<t> (namely 2 methods equals , 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 of t, , therefore signal equals , gethashcode should work correctly t. (after all, defining new type without explicitly implementing equals , 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:

  1. 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.
  2. 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

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -