I have a foolish doubt.Generally "System.Object" implements "Equals". When I implements IEquatable interface i can give custom definition ( I believe so) to my "Equals".
so the professor class implementation is equal to
class Professor:System.Object,IEquatable
since there are different definitions of System.Equals ,and IEquatable's Equals ,Why did not C# report error?.Because I am not overriding "Equals" and even not Hiding "Equals" using new keyword.
class Professor : IEquatable<Professor>
{
public string Name { get; set; }
public bool Equals(Professor cust)
{
if (cust == null) return false;
return cust.Name == this.Name;
}
}
You are neither overriding nor hiding Object.Equals()
because your version takes Professor as a parameter type - not object. Your are overloading the Equals() method.
C# allows two methods with the same name to differ on the type of the argument(s) that they accept. This is referred to as overloading - it can be viewed as compile-time polymorphism.
Overriding (which you could, and probably should also do) alters the implementation of a method from its version in a base class. It is the basis for runtime type polymorphism.
Hiding is a less common technique that allows a derived class to mask a version of a method in a base class. Based on the type of the reference through which you make the call, you may either get the base class version (if called through a base class reference) or the derived class version (if called through a derived type reference).
On your second question, you should use IEquatable<T>
when there are semantics for comparing 'equality' of two instances that is separate from reference equality.
You should implement IComparable
or IComparable<T>
when there are semantics for ordering items. Meaning they can be less than, greater than, or equivalent.
The Object.Equals method accepts an object of type 'object' as its parameter. Your Equals method accepts an object of type 'Professor' as its parameter. Both of these methods can co-exist because it is legal to differ two identically-named methods by their parameter list; this is call method overloading.
You don't need to explicitly implement IEquatable if all you want to do is override the default Equals() implementation.
You can just do something like this:
class Professor
{
public string Name { get; set; }
public override bool Equals(object cust)
{
if (cust == null || !(cust is Professor)) return false;
return cust.Name == this.Name;
}
}
Be aware that if you override Equals() you also should override GetHashCode() to ensure proper operation of dictionaries and other collections that make use of hashing to differentiate between objects. Here's the MSDN page guidelines for overriding Equals().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With