Using 'is' with a dynamic type

Since the following appears to be illegal...

class MyClass

{

public override bool Equals (object obj)

{

if ( ! obj is typeof ( this )) // <== Syntax error

return false;

// other comparison stuff

}

}

What is the easiest way to do the above Performance is not an issue as the code is just responding to user actions.

The reason for wanting to do this is deep inheritance and the use of Activator.CreateInstance.

I also have some confusion over whether it is better to overide Equals(obj) or if it is better to create Equals(MyClass) at each level of inheritance.

Paul



Answer this question

Using 'is' with a dynamic type

  • peter lam

    Guess like that:

    if ((obj==null) || (object.GetType() != this.GetType()))
    return false;


  • Brent Pranger

    That's what I did in the end. I assume the 'is' form is quicker and that is why it is used.

    Thanks


  • Paul Pisarek

    Well, and as you discovered yourself, you need a fixed type there during compile time and cannot use a variable there representing a type or something else
  • Using 'is' with a dynamic type