Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "is" keyword and the override of Equals method

Tags:

c#

.net

The documentation for the keyword "is" states that:

The is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.

What does it mean in practice? Is it wrong to use it to check if a struct is a certain type? For example,

public struct Point2D
{
    public int X;
    public int Y;

    ...

    public override bool Equals(Object value)
    {
        if (value != null && value is Point2D)   // or if (value != null && GetType() == value.GetType())
        {
            Point2D right = (Point2D)value;
            return (X == right.X && Y == right.Y);
        }
        else return false;
    }

    ...
}
like image 941
enzom83 Avatar asked Feb 07 '12 23:02

enzom83


People also ask

Can you override equals method?

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.

What is the reason for overriding equals () method?

We can override the equals method in our class to check whether two objects have same data or not.

What is equal () method in Java?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

What are equals () and hashCode () overriding rules?

if a class overrides equals, it must override hashCode. when they are both overridden, equals and hashCode must use the same set of fields. if two objects are equal, then their hashCode values must be equal as well. if the object is immutable, then hashCode is a candidate for caching and lazy initialization.


1 Answers

Checking whether a struct is a certain type is fine. The documentation means that user-defined explicit and implicit conversion operators are not evaluated when considering whether the given object is of the specified type, even if there is a user-defined operator that can convert it to said type.

like image 165
Chris Shain Avatar answered Jan 30 '23 23:01

Chris Shain