Jan 26 2005

VB.NET: MsgBox() or MessageBox.Show()?

Published by at 2:41 pm under .NET

This is an old article and the information contained within it may be out of date, not reflect my current views and/or contain broken links. If you feel this article is still valid and requires updating, you can use the contact form to let me know. However, I make no guarantee that it will get updated.

I’m currently using VB.NET as my main language because thats what my project at work requires. But having come from programming in VB6 I was just wondering if I’m using some of the old VB6 constructs and functions just because they are still there or because they really are the best way of doing things in VB.NET.

I think the best way to demonstrate what I mean is the MsgBox() function. This function takes several parameters are displays a little message box to the user with one or more buttons for them to press to indicate their response. As far as I am aware (but I may be wrong), the MsgBox function was the only way to do this in VB6 without writing your own version of the message box.

In VB.NET, however, there is now the MessageBox class in the System.Windows.Forms namespace. Out of habbit, though, I am still using the MsgBox function simple because its there. MsgBox is actually in the Microsoft.VisualBasic namespace which gets automatically imported into a VB.NET project.

But which is better: the MsgBox() function, or the MessageBox class? There’s only one way to find out… use Lutz Roeders .NET Reflector tool to take a look at the innards of both of these.

When you have a look inside it is easy to see which method should be used to display a message box. It appears that Microsoft.VisualBasic.MsgBox() does some exception check and then passes the call onto System.Windows.Forms.MessageBox.Show() this then does pretty much the same exception checking and the passes the call onto System.Windows.Forms.SafeNativeMethods.MessageBox() which is itself a wrapper for a win32 API call to user32.dll.

So which is the best method to show a message box? Between Microsoft.VisualBasic.MsgBox() and System.Windows.Forms.MessageBox.Show() you should really use the latter, System.Windows.Forms.MessageBox. Firstly it removes an unnecessary layer of exception checking and secondly using the Microsoft.VisualBasic namespace will reduce your ability to port your application to another platform/language.

15 responses so far