Avoiding IsNothing()

A few days ago I posted about my surprise on finding out what IsNothing() really does. After reviewing more code I found out another reason you should avoid this: It accepts value types! Obviously, since IsNothing() is a function that accepts an 'object', you can pass anything you want to it. If it's a value type, .NET will box it up into an object and pass it to IsNothing -- which will always return false on a boxed value!

This really is a discipline issue and you shouldn't be checking for null (Nothing) value types. The VB.NET compiler will check the "Is Nothing" style syntax and won't compile if you attempt to do an "Is Nothing" on a value type. But the IsNothing() function compiles without complaints.

We're removing all occurrences of "IsNothing()" and replacing them with "Is Nothing".

3 Comments

  • Nice tip...



    I've been using IsNothing(), after seeing it a number of times in MS examples.



    Guess I'll go back to "Is Nothing" too.



    Thanks for posting this...

  • I think the reason this is here is the legacy code support that VB seems to constantly retain through it's iterations. Like in VB6 using CALL seems to do the same as ommiting the CALL (except you have to provide the () at the end of the method) Which was carried over from langauges before..

  • Oh and another thing! I think another reason for IsNothing is for the VARIANT type. Since VARIANT (in VBScript and VB6) lets you make it a value type or object type, using IsNothing was a safe way to NOT get a runtime error because you could pass it the value type or object type, but if you used Is Nothing then you would get a runtime error (since VBScript doesn't compile you wouldn't see the error until it happened)



    NOT that you should be using the SAME variable for objects and values.. geez .. :)

Comments have been disabled for this content.