Test an object for NOT being a type
Question
I know how to test an object to see if it is of a type, using the IS keyword e.g.
if (foo is bar)
{
//do something here
}
but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result.
BTW - I have a horrible feeling this is soooo obvious, so apologies in advance...
Solution
if (!(foo is bar)) {
}
OTHER TIPS
You can also use the as operator.
The as operator is used to perform conversions between compatible types.
bar aBar = foo as bar; // aBar is null if foo is not bar
There is no specific keyword
if (!(foo is bar)) ...
if (foo.GetType() != bar.GetType()) .. // foo & bar should be on the same level of type hierarchy
You should clarify whether you want to test that an object is exactly a certain type or assignable from a certain type. For example:
public class Foo : Bar {}
And suppose you have:
Foo foo = new Foo();
If you want to know whether foo is not Bar(), then you would do this:
if(!(foo.GetType() == tyepof(Bar))) {...}
But if you want to make sure that foo does not derive from Bar, then an easy check is to use the as keyword.
Bar bar = foo as Bar;
if(bar == null) {/* foo is not a bar */}