Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there "is not" keyword in c#?

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
 }
like image 959
dexter Avatar asked Dec 02 '10 21:12

dexter


3 Answers

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

like image 169
BoltClock Avatar answered Oct 16 '22 15:10

BoltClock


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.

like image 34
StriplingWarrior Avatar answered Oct 16 '22 15:10

StriplingWarrior


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  }
like image 4
Daniel Mošmondor Avatar answered Oct 16 '22 15:10

Daniel Mošmondor