7

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;
    }

    ...
}
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
enzom83
  • 8,080
  • 10
  • 68
  • 114
  • 1
    It is wrongish, value.GetType() == typeof(Point2D) protects you against refactoring accidents. – Hans Passant Feb 08 '12 at 00:59
  • 1
    Is [this](http://stackoverflow.com/questions/983030/type-checking-typeof-gettype-or-is) the reason? – enzom83 Feb 08 '12 at 13:39
  • @enzom83 That is correct. `is` could be appropriate for this case, if you care about inheriting from Point2D, and want children to also have this same logic (by default) – McKay Feb 08 '12 at 16:09

1 Answers1

6

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.

Chris Shain
  • 50,833
  • 6
  • 93
  • 125