Question

I don't have much experience with VB.NET and although I've searched, I can't find an answer to the following:

Say I have a Dim myVar As MyClass, and then a function in which I intend to initialize it such as Public Sub MyInit(ByRef myVar As MyClass). Attempting to call this method is giving me a null reference error in the compiler, stating that I should initialize the variable first (but I intend to put that functionality in my method!).

Any thoughts in how I could achieve what I'm attempting here?

PS: I reckon it'd make more sense to create an Initialize() method in MyClass, or to make a Public Function MyClassInitialize() As MyClass, but in my particular scenario this is not possible.

Was it helpful?

Solution

If you're just worried about the Variable 'myVar' is passed by reference before it has been assigned a value warning, you can just change the declaration to Dim myVar as MyClass = Nothing.

If you're writing the MyInit sub, you could also turn it into a function that returns an instance of MyClass:

Public Function MyInit() As MyClass
    Dim myLocalVar As New MyClass()
    '... initialization here
    Return myLocalVar
End Function

...

Dim myVar As MyClass = MyInit()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top