It just makes sense sometimes to check if an object is not type of X, so you need to do this instead:
if(this.GetType() != typeof(X))
{
//Do my thing.
}
Which is a bit cumbersome to my opinion, would not something like this be nicer:
if(this is not X)
{
//Do my thing
}
How about the logical NOT operator !
, fits the description of the word 'not' just fine:
if (!(this is X))
{
//Do my thing
}
As others have pointed out though, is
is also used to check if an object's class inherits from some class or implements some interface, which is rather different from GetType()
.
Both CodeInChaos and StriplingWarrior have reasonable explanations for why there isn't a not
keyword in C#.
Adding a keyword to a language adds complexity. Adding a keyword to a language after the initial specification could cause breaking changes for people upgrading. So keywords generally only get added if there's a very strong case for them. In this case, as the other answers point out, it is very easy to use the bang operator:
if (!(pero is Human)) ...
... which a typical C# (/C/C++/Java) developer would read "if not (pero is human)". So there's not much justification for a special keyword.
Use good ol' bang symbol:
if (!(pero is Human))
{
}
BTW, is
is different, because it catches not only leaf derived class, but whole hierarchy of it, both interfaces and classes.
So, for
class Human: ICanSpeak, Mamal
{
...
}
Human h;
if (h is Human) { will be true }
if (h is ICanSpeak) { will be true }
if (h is Mamal) { will also be true }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With