user317808
user317808

Reputation: 81

VB.NET: Use Class Name as Expression

I'm not sure if this is possible but I would like to associate a class name reference to a shared member method / property / variable. Consider:

Public Class UserParameters

    Public Shared Reference As Object

    Public Shared Function GetReference() As Object
        Return Reference
    End Function

End Class

In another part of the program I would like to simply call UserParameters and have it return Reference either by aliasing GetReference or the variable directly.

I am trying to emulate the Application, Request, or Session variable: Session(0) = Session.Item(0)

Any suggestions would be greatly appreciated.

Upvotes: 2

Views: 860

Answers (1)

Frazell Thomas
Frazell Thomas

Reputation: 6111

You can't return an instance member from a static method directly (the static method can't access instance members because it isn't instantiated with the rest of the class, only one copy of a static method exists).

If you need to setup a class in such a way that you can return an instance from a static method you would need to do something similar to the following:

Public Class SampleClass

    Private Sub New()
        'Do something here
    End Sub

    Public Shared Function GetSample() As SampleClass
        Dim SampleClass As SampleClass
        SampleClass = New SampleClass

        SampleClass.Sample = "Test"

        Return SampleClass
    End Function

    Private _SampleString As String
    Public Property Sample As String
        Get
            Return _SampleString
        End Get
        Private Set(ByVal value As String)
            _SampleString = value
        End Set
    End Property

End Class

Public Class SampleClass2

    Public Sub New()
        'Here you can access the sample class in the manner you expect
        Dim Sample As SampleClass = SampleClass.GetSample
        'This would output "Test"
        Debug.Fail(Sample.Sample)
    End Sub
End Class

This method is used in various places in the CLR. Such as the System.Net.WebRequest class. where it is instantiated in this manner in usage:

' Create a request for the URL.         
        Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/default.html")

Upvotes: 1

Related Questions