views:

239

answers:

4

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...

+13  A: 
if (!(foo is bar)) {
}
Vinko Vrsalovic
+1  A: 

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
aku
+4  A: 

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
John
Is this 'cryptic and weird' or taking advantage of language features?
Yar
+1  A: 

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 */}
Haacked
I love the foo as bar bit, because you will no doubt want to DO something with foo if it is a Bar, so you might as well code for that situation.
Yar