KnowDotNet NetRefactor

A Few Shortcuts in .NET

Less really is more!

by William Ryan
Print this Article Discuss in Forums

IF YOU EMBRACE the whole "Less Code is More" paradigm put forth by Microsoft, Visual Studio .Net has a whole host of features to help you achieve your goal.  In this simple example, you'll learn how to use some built in features of VS.NET to Shave off some code from calls to a Form's .ShowDialog method.

Most any non-trivial application these days will involve the use of a Modal Dialog Form.  This might take the form (no pun intended) of a MessageBox or it may be a custom form such as  a Log-in screen or Custom Warning/Notification.  This isn't the most dramatic example of using some new shortcut features in your code, but I originally saw it used by Charles Petzold in Programming Windows With C# by Microsoft Press and found it a pretty cool way to do things.  You can easily expand this methodology to include custom enumerations and methods like a QueryResult Enum or some other common method wherein you retrieve a return value.

So take for example a case where you show a modal dialog box and want a result.  Traditionally you'd do something like this:

VB.NET
  Dim f As New frmLogin
        
Dim r As New DialogResult

        r = f.ShowDialog
        
If r = DialogResult.Abort Then

        ElseIf r = DialogResult.Cancel Then

            'On and on
        End If


C#

Form2 f = new Form2();
  
if(f.ShowDialog() == DialogResult.OK)
   {
       :
   }
  
else
  {

  }

You could cut out a step or two by using this approach but it's still limiting.

If f.ShowDialog = DialogResult.Abort Then

            'Else if .... you get the idea

        End If


Each time through you'd have to roll out the ShowDialog Code which would make for a miserable user experience.  However, since ShowDialog is actually a method which returns a Dialog result, you can put it right in a SELECT CASE statement in VB.NET or a switch() statement in C#.



VB.NET
Dim f As New frmFind
        
Select Case f.ShowDialog
            
Case DialogResult.Abort

            
Case DialogResult.Cancel

            
Case DialogResult.Ignore

            
Case DialogResult.No

            
Case DialogResult.None

            
Case DialogResult.OK

            
Case DialogResult.Retry

            
Case DialogResult.Yes

        
End Select


C#

Form2 f = new Form2();
    
switch(f.ShowDialog())
      {
        
case DialogResult.OK:

        
case DialogResult.Cancel:

        
case DialogResult.No:

        
case DialogResult.Yes:


     }

Now, this is a simple shortcut that frees you from Declaring a DialogResult and gives you an abbreviated syntax.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing