Batman
Batman

Reputation: 702

creating a shared variable with inheritance

My question is in relation to the below question:

In VB.net, How can I access to a function in a class from an other function in a nested class?

By setting the variable h shared, are you making that variable available to all instances of the class as a single or static variable thereby creating the possibility for problems in the asker's future endeavors? Or is my understanding of VB.net skewed?

If I'm right would that mean that the code would the need to be arranged like this:

Class N
    Dim h
    Class n
        Implements iInterface
        Sub f()
            h = 5
        End Sub
    End Class
End Class

And instead create an instance of the object to use in consuming code?

Upvotes: 1

Views: 1002

Answers (1)

the_lotus
the_lotus

Reputation: 12748

A shared variable isn't part of the instantiated object. If you write

Dim o As New N
o.h = 1

Assuming h is shared, you will get a warning. You have to call it like this.

N.h = 1

When you have code in the class itself, you don't need to specify the class name. His code is actually

Class N
    Shared h = 4

    Class n
        Implements iInterface
        Sub f()
            N.h = 5
        End Sub
    End Class
End Class

Maybe this will help you understand it a bit more. This clearly show that each instance of n will be sharing the same h variable. Let's add a new function

Class N
    Shared h = 4

    Class n
        Implements iInterface
        Sub f()
            h = 5
        End Sub
        Sub ff()
            h = 12
        End Sub
        Function GetH() As Integer
            Return h
        End Sub
    End Class
End Class

Dim o1 As New n
Dim o2 As New n

o1.f()
o2.ff()

Console.WriteLine(o1.GetH()) ' This will print 12
Console.WriteLine(o2.GetH()) ' This will print 12

I think his question didn't have enough information to indicate if the shared variable will cause problem or not.

Upvotes: 1

Related Questions