Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form cannot refer to itself through its default instance on shared call

Consider the following code, in a brand new WinForms .NET 4.0 application, with default settings:

Public Class Form1
  Private Sub AAA()
    Form1.AAA(Nothing) 'cannot refer to itself through its default instance; use 'Me' instead.
  End Sub

  Private Shared Sub AAA(str As String)
  End Sub
End Class

I am getting this error:

{FORM_CLASS_NAME} cannot refer to itself through its default instance; use 'Me' instead.

I also get this warning at the same line:

Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.

Assuming default instance is meant here, it ends up in an infinite loop - VS suggests to change Me.AAA() to Form1.AAA(), and then back. AAA() works in both.

Converting Private Sub AAA() to Shared solves the error. It seems like from Microsoft's point of view, all overloads must be shared, if at least one is. Or you get this default instance confusion. Why?

To clarify, I do not want to use default instance here, just do a shared call.

If anyone encountered the same situation, please advise.

like image 201
Neolisk Avatar asked Mar 12 '13 14:03

Neolisk


1 Answers

Creating a variable alias that has the same name as the type of the Form class is without a doubt the single most disastrous VB.NET problem. But it was necessary to give VB6 developers a fighting chance to move to VB.NET.

The workaround is to stop trying to be explicit about what method you want to call. This compiles fine and is unambiguous, at least in your snippet:

  Private Sub AAA()
       AAA(Nothing)       '' fine
  End Sub

If that really, really hurts then simply swapping the two methods removes the ambiguity:

Private Shared Sub AAA(str As String)
End Sub

Private Sub AAA()
    Form1.AAA(Nothing)    '' fine
End Sub
like image 123
Hans Passant Avatar answered Sep 26 '22 06:09

Hans Passant