One of the most underused operator in VB.NET is the IsNot operator. That’s because there was really no significant use of introducing this operator. All was going well without this operator too. I find that many experienced programmers are still unaware of the existence of this operator in VB.NET.
The old way of doing things was:
If Not object1 Is object2 Then whatever
If Not myObject Is Nothing Then DoSomething() If Not myObject Is TextBox1 Then DoSomething()
The new way with the IsNot operator would be:
If object1 IsNot object2 Then whatever
If myObject IsNot Nothing Then DoSomething() If myObject IsNot TextBox1 Then DoSomething()
So you may ask why introduce something into the language which is not required at all? And why should we use it anyways?
I can think of a couple of reasons for this:
- You never do “If Not a = b Then DoSomething”, or “If Not a <= b Then DoSomething”. You will always do “If a <> b Then DoSomething” or “If a > b Then DoSomething” instead. Though it’s your free will to choose either ways. Same is the case with the Is operator. Why should you be forced to do “If Not object Is Nothing Then DoSomething”. And that raises the need of this IsNot operator.
- Visual Basic has always been more of a human type language rather than programmer type language. From ever since it exists (even its predecessors), it was never a programmer type language. So it doesn’t fit into good English when you say “If Not object is Nothing” while the new syntax is more English like “If object IsNot Nothing”. It is simpler to understand; and that’s what Visual Basic is.
- You make one negation and one comparison when using the old coding style. While you do just one comparison with the IsNot operator. So the IsNot operator should save you one CPU instruction. Though this is not a big ado, since compliers these days are smart enough to preprocess and optimize such situations.
One thing I could never understand is why it doesn’t work with the TypeOf operator. It could be possible that there was some difficulty implementing that syntax. Or it missed the attention of the product development team altogether. 🙂
e.g. The equivalent of
If Not TypeOf myObject Is TextBox Then DoSomething()
Should have been:
If TypeOf myObject IsNot TextBox Then DoSomething()
Unfortunately that doesn’t work.
So since you know about this IsNot operator now, I’ll recommend that you start using it actively in your daily coding wherever applicable for either of the two reasons given above you are satisfied with. 🙂