Access of shared member...qualifying expression may not be evaluated

obiewoncanoli

New member
Joined
Jun 22, 2010
Messages
1
Programming Experience
10+
re: Access of shared member constant member enum member or nested type through an instance qualifying expression may not be evaluated

I understand that this warning means that you should not reference a shared member via an instance. However, in my test case Test2.t.x("3"), I don't understand why it thinks I'm using an instance, since t is also a shared member.

Also, note Test3. See what happens when you change declaration of GetObject() As Object to As Test3. I think I understand the behavior (not eval'd until runtime), but I'd appreciate some thoughts/insights. Thanks.


Module Module1

Class Test1
Public Shared Sub x(ByVal s As String)
Console.WriteLine("test1 - " & s)
End Sub
End Class


Class Test2
Public Shared t As Test1
End Class


Public Class Test3
Public Sub New()
Console.WriteLine("New Test3")
End Sub

Public Shared NumCreations As Integer = 0

Public Shared Function GetObject() As Object 'As Test3
NumCreations += 1
Return New Test3
End Function
End Class



Sub Main()
Dim t As Test1
t.x("1")

Test1.x("2")

Test2.t.x("3")


Console.WriteLine(Test3.GetObject().NumCreations)

Console.ReadLine()

End Sub


End Module
 
't' may be a Shared member but it returns an instance of the Test1 class. This:
VB.NET:
Test2.t.x("3")
is equivalent to this:
VB.NET:
Dim obj As Test1 = Test2.t

obj.x("3")
As you can see, that is calling 'x' on a Test1 object, not on the Test1 class itself. If you want to call a Shared member then you ALWAYS call it directly on the class and NOTHING else.

Your last question relates to late-binding. With Option Strict Off, which it is by default, VB will let you access members that the compiler cannot confirm exist. There is extra work done at run time to access the members and an exception thrown if they don't exist. You should ALWAYS turn Option Strict On and NEVER use late-binding except in those situations where it's expressly needed, e.g. Office automation.
 
Hello. Try,

VB.NET:
...Code

[COLOR="green"]Public Shared t As Test1[/COLOR] - [B]Add[/B]

Sub Main()
    [COLOR="red"]Dim t As Test1[/COLOR] - [B]Remove[/B]
    t.x("1")
    Test1.x("2")
    Test2.t.x("3")

...Code

See if this works.
 
Back
Top