KnowDotNet

C# and VB.NET Gotcha - Select Case Using Nothing Does Not Raise Exception

Select Case (Nothing/null) Matches Nothing

by Les Smith

In C# and VB.Net a Select Case against a variable set to Nothing will not throw an exception; watch out.  Check out the following code.

   Select Case processType
      
Case "I" ' Move from FTP to working dir
         .ProcessType = FileMoverLib.FileMove.ProcessTypeMoveFromFTP
      
Case "O" ' move from working folder to FTP
         .ProcessType = FileMove.ProcessTypeMoveToFTP
      
Case Else
         Throw New Exception("processType not set in ProcessOneMoverObject")
   End Select

If processType is Nothing the code falls through to the Case Else.  I happened to be debugging and was trying to cause an exception to test my exeption logging and so I allowed processType to be Nothing.  I had the Case Else code but did not have any code under it.  I was surprised to find that I fell into the empty Case Else.

I thought maybe C# might be a little tighter, but gues what...it's not!  The following code works the same.  Control reaches the default Console.WriteLine.

      static void Main(string[] args)
      {

        
string s3 = null;
        
switch (s3)
         {
            
case "a":
                
// do something
                 break;

            
default:
              
Console.WriteLine("Control should not get here.");
              
break;
         }

This is another simple tip but it could save you some headaches.

Have you tried our newest product, Visual Class Organizer?  You'll be amazed how easy it is to keep the code in your code windows organized.  TRY IT FREE FOR 30 DAYS BY CLICKING HERE.



If you are developing in C# and haven't tried CSharpCompleter, you are wasting valuable time typing hundreds of braces {} daily needlessly.  Try CSharpCompleter for 30 DAYS FREE.



Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog.