How can I declass this variable?

Angelus

Newcomer
Joined
Nov 12, 2003
Messages
16
I am writing a class and has one variable(X) that will use anywhere in this class (Class A). So I declare X in Module and initialize X at New subrouting but I read in MSDN that declaring variable in Module variable will be implicitly Shared.

What I want is to declare X in Class A that X can be use anywhere in Class A but has its own value in each instance of Class A.

I also use Friend key word but it not working when I have more than one instance.
 
Instance variables

Declare X in the class body but outside any methods:

Visual Basic:
Public Class MyClass
    Private X As Integer

    'Example method
    Public Sub Foo()
        X = 10
    End Sub

    'More methods etc...
End Class

Good luck :cool:
 
Re: Instance variables

I believe Angelus should consider reading the basics of Object Oriented Programming in .Net. I believe it helps to have the basics intact.

Cheers. :D
 
Re: Instance variables

No. I need something for Variable X like this

'MyClass.VB File
Public Class MyClass

'Example method
Public Sub New(val1 as integer)
'Initial X Here
X = val1
End Sub

Public Sub Method1()
Use X Here

End Sub
'More methods etc...
End Class

'Other File In the same project
Public Module MyModule

Public Function CalX()
Also use X Here
End Sub

End Module


If I declare Friend X as integer in MyModule, X can be used in MyModule and MyClass as well but X still be as Shared. So when I use more than 1 instance of MyClass in other program, X value will be changed to val1 that applied to the last instance of MyClass.
 
Exposing class variables as properties

As amir100 suggests, you should get a book on the subject - and stop using modules. If you want X to be specific to instances of MyClass and be accessible outside MyClass then you need to expose it as a property:

Visual Basic:
'MyClass.VB File
Public Class MyClass

    Private m_X As Integer '<--- X is declared here

    'This property allows X to be accessed outside MyClass
    Public Property X As Integer
        Get
            Return m_X
        End Get
        Set(ByVal value As Integer)
            m_X = value
        End Set
    End Property

    'Example method
    Public Sub New(val1 As Integer)
        'Initialize X Here
        X = val1
    End Sub

    Public Sub Method1()
        'Use X Here
    End Sub

    'More methods etc...
End Class

Visual Basic:
'Other File In the same project
Public Module MyModule

    Public Function CalX(ByVal obj As MyClass)
        'Also use X Here
        obj.X = obj.X + 1
    End Sub

End Module

I seriously recommend you get hold of a good beginners VB.Net book as this is a very fundamental and important concept. Hopefully it will also lead you away from using modules, which should be avoided.

Good luck :)
 
Back
Top