0

I have a namespace with a class inside it with another class inside that, i.e.

namespace MySpace
    public class MainClass
        public class SubClass
            public x as integer
            public z as integer
        end class

        public function Foo ()
            dim y as SubClass
            y.x = 5
            return
        end function
    end class
end namespace

except the line y.x = 5 gets underlined with the tip "Variable y is used before it has been assigned a value. A null exception could result at runtime"

Basically I want to be able to have the multiple items that Foo assigns then available to whatever other code is using the MainClass class. What is the safest way to do this? If I was doing this in C I would have used a struct but apparently they are less efficient in VB?

1 Answer 1

2

You could make x and z shared:

    Public Class SubClass
        Public Shared x As Integer
        Public Shared z As Integer
    End Class

Or you can instantiate a class-level variable:

Public Class MainClass

    Private m_objSubClass As New SubClass2

and call like so:

    Public Function Foo()
        'Shared
        SubClass.x = 5
        'Instantiated Class-Level variable
        m_objSubClass.x = 5
    End Function

If the Subclass needs to be accessed by other classes then expose the instantiated version through a Property instead of just a private variable (or return the instantiated version in your function).

Return m_objSubClass

Finally, if your values do not need to persist, you could simply instantiate a Subclass2 in the function:

Dim objSubClass2 As New SubClass2
objSubClass2.X = 5
Return objSubClass2 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, How would I make it so that the properties of subclass are available publicly (outside of mainClass) while the members are available only to mainClass but not outside of it?
Have a Public Property on your Main Class that returns m_objSubClass. That way it would be "objInstanceOfMainClass.PropertyNameOfSubClass.X = 5"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.