0

I have a class, MyClass, declared as public, with a Shared method test():

Public Class MyClass
  Public Shared Function test()
    Return "sdfg"
  End Function

  ' snip other non-shared methods
End Class

This Class is located in the App_Code directory of the website, and appears to be visible, as I can instantiate an instance of the Class from any of the sites scripts.

My issue relates specifically to accessing the Shared method test(). Trying to get this working, I have the following code in Page_Load() of one of the scripts:

Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
  Response.Write MyClass.test()

  Dim myClassVar As MyClass = new MyClass()
  myClassVar.nonSharedMethod()
End Sub

If I comment out Response.Write MyClass.test(), everything works fine and I can use the Class - however, trying to access the Shared method, I get the following error:

Local variable 'myClass' cannot be referred to before it is declared

Any pointers as to what I am doing wrong?

3
  • 1
    I'm guessing that in obfuscating this code for posting purposes, you've masked the fact that you have a variable with the name MyClass also declared in your page load (that is what the error is basically saying). Commented Jul 26, 2011 at 13:42
  • 1
    I realise that this example is probably an abstraction, but does this still happen if you change the class name to AClass instead of MyClass? MyClass is a keyword in VB.Net, this could be causing your problme. Commented Jul 26, 2011 at 13:51
  • @Damien_The_Unbeliever, yes, that is exactly what was happening... I had a variable of type MyClass called myClass, and VB is apparently treating myCLass == MyClass in terms of the variable name. Interesting, thanks for the help. Can you post this as a solution so I can mark it answered? Commented Jul 26, 2011 at 14:04

1 Answer 1

2

I'm guessing that in obfuscating this code for posting purposes, you've masked the fact that you have a variable with the name MyClass also declared in your page load (that is what the error is basically saying).

Visual Basic is a case insensitive language. Declaring your variable as myClass is the same as declaring it as MYCLASS or myclass, and the line MyClass.test() will be resolving the name MyClass to that variable - which as the error indicates, hasn't been declared yet.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.