1

To check if an object is of a given type in C#:

if(myObj is MyClass)
{
     //....
}

To check if it is not of a given type:

if(!(myObj is MyClass))
{
     //....
}

Is there a more readable way to express the same logic?

For example, if I could write this it would be easier to read.

if(myObj is not MyClass)
{
     //....
}
Reactgular
  • 52,335
  • 19
  • 158
  • 208

2 Answers2

6

You can try using some extention method like this, just to make it more readable as you want:

public static class ObjectExtension
{
    public static bool IsNot<T>(this object o)
    {
        return !(o is T);
    }
}
//Use it
if(myObj.IsNot<MyClass>()){
  //...
}
King King
  • 61,710
  • 16
  • 105
  • 130
  • I've never seen this done before, thanks. Reminds me of traits in PHP. – Reactgular Sep 19 '13 at 22:18
  • @MathewFoscarini that's some combination of `extension method` and `generics`, I think it's just the most beautiful work-around. – King King Sep 19 '13 at 22:19
  • You might wish to add a generic constraint to ensure that this is not used with value types. Edit: I guess `is` works with value types after all. But will this cause boxing? – Chris Dunaway Sep 19 '13 at 22:22
  • @ChrisDunaway wow, after your comment, I've done some test, it's still useful for testing on `struct`, some object has `struct` boxed inside it, we still need to check that case. I don't think there is any problem here. – King King Sep 19 '13 at 22:33
4

You could take the same approach and make it more verbose:

If (myObj is MyClass == false) ;
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136