Accessing 'nested' class properties

J

John Dann

I'm realising that there's something important that I don't understand
about acccessing class properties. In fact I'm not even sure that I
can explain clearly what it is that I don't understand! But let me
try:

Let's say that I have a specific parameter value that needs to be
available to several different classes within a program. What I'm
doing currently is to store this specific value in a property of
MyClass1. This class is then instantiated in MyClass2 and then the
property is actually assigned in Form1. So (without showing the
intermediate declarations) I'd have:

Public Class Form1
dim oMyClass2 as New MyClass2
Sub etc
oMyClass2.oMyClass1.MyProperty = MyValue
End class

Hopefully this is OK so far.

But now say I want to access the current value of MyValue from within
a couple of other distinct classes, eg MyClass3 and MyClass4. I guess
the only way of getting at MyValue is to declare a reference to Form1
in both classes MyClass3 and MyClass4.

Public Class MyClass3
dim frm1 as New Form1
Sub etc
x3 = frm1.oMyClass2.oMyClass1.MyValue
End Class

and

Public Class MyClass4
dim frm1 as New Form1
Sub etc
x4 = frm1.oMyClass2.oMyClass1.MyValue
End Class

I'm left with 2 questions:

First, I'm a little uncertain as to whether x3 and x4 will
categorically be assigned to the same value.

Second, is there a better way of handling this? I guess with VB6 I'd
have declared a global variable that didn't need any qualification as
to which its parent class might have been. But I don't seem to have
that option with .Net

Thanks to anyone able to make sense of this.
JGD
 
R

Robin Tucker

Yes, you can create global singletons in .NET. Encapsulate your variable
into a class and create a single instance of this class in a module. The
class shown below also throws an exception if you attempt to create more
than one instance of the singleton (I didn't check or compile this code).


Module Module1

Public Class AB

' Your reference.......

Private m_Ref As SomeClass


' True if we already created an instance.

Private Shared m_bCreated As Boolean = False



' Implement constructor to check to see if we already created one.

Public Sub New()

If m_bCreated Then
Throw New Exception("Singleton already created.")
End If

m_bCreated = True
End Sub



' Get/Set the reference

Public Property TheRef() As SomeClass

Get
Return m_Ref
End Get

Set(ByVal Value As SomeClass)
m_Ref = Value
End Set

End Property

End Class





' Declare the global singleton.

Public s_AB As New AB


End Module
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top