.net - IEquatable<T> - Best practice override for .Equals(object obj) in C# -


whenever write new class or struct hold data, may need compared, implement iequatable<t> provides class/struct typed .equals(t other) method.

example:

public struct radius : iequatable<radius> {     public int32 topleft { get; set; }     public int32 topright { get; set; }     public int32 bottomleft { get; set; }     public int32 bottomright { get; set; }      public bool equals(radius other)     {         return this.topleft == other.topleft             && this.topright == other.topright             && this.bottomleft == other.bottomleft             && this.bottomright == other.bottomright;     } } 

as providing implementation .equals(radius other), should override default implementation (.equals(object obj))

i have 2 options here, , question is, of these implementations better?

option 1 use casting:

public override bool equals(object obj) {     return this.equals((radius)obj); } 

option 2 use "as" keyword:

public override bool equals(object obj) {     return this.equals(obj radius); } 

my reason asking is, using casting throw exception if obj cannot cast radius, whereas as resolve null if cannot cast, therefore checks this against null, without throwing exception; better throw exception, or return false?

edit: has been pointed out quite few fellow so'ers, structs cannot null, therefore second option not apply struct. therefore question springs mind: should overridden implementation of .equals(object obj) identical structs , classes?

the equals() method must never throw exception.

an object of different type merely unequal.

quoting documentation:

implementations of equals must not throw exceptions; should return value. example, if obj null, equals method should return false instead of throwing argumentnullexception.


Comments

Popular posts from this blog

Need help in packaging app using TideSDK on Windows -

java - Why does my date parsing return a weird date? -

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -