VB.NET Shares a little too much

A thread today on using the System.Diagnostics.Process class highlights one of the more confusing aspects of VB.NET (or VS.NET depending on how you want to look at it). Intelliense will list Shared (static in C#) members when showing members on an instance variable. Take the following sample code:

Option Strict On
Option Explicit On 

Imports System
Imports System.Diagnostics

Public Class Class1

    Shared Sub Main()

    End Sub

    Public Sub UseInstance()
        Dim p As Process = New Process

        p.Start("http://www.microsoft.com")
    End Sub

    Public Sub UseShared()
        Process.Start("http://www.microsoft.com")
    End Sub

End Class

In 'UseInstance' the "Start" method appears to be a method on an instance of Process. But then in 'UseShared', we see that "Start" is a shared method on the Process class. Further, if you compile this code and check it out with ILDASM you'll see that both calls compile to the same IL:

ldstr      "http://www.microsoft.com"
call       class [System]System.Diagnostics.Process [System]System.Diagnostics.Process::Start(string)

So be careful when you're using VB.NET. Some methods may not need a class instance to be called. This could be especially annoying on a class that implements IDisposable. You'd create an object that would hang around longer than normal (since it's Disposable) but may never actually use it if the method you're calling is shared! Perhaps VS.NET 2005 could make this configurable...

2 Comments

  • <sarcasm>Its probably like that because VB.Net users dont understand the difference between instance and static methods</sarcasm>



    seriously though that has always annoyed me with VB.

  • Well, VB2005 fixes this the C# way (you only see instance members on instances and shared member on the class). IMO, they should have shown all members (for discoverability) and autocorrect it to the class name when you hit enter.

Comments have been disabled for this content.