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;
}
...
}
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.
We can override the equals method in our class to check whether two objects have same data or not.
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
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.
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.
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