0

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.

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
Sebastián Vansteenkiste
  • 2,234
  • 1
  • 19
  • 29
  • one way to avoid it is to give myVar more scope so you dont have to pass it (a NullReference) to anything or anywhere to initialize it. see also: http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Ňɏssa Pøngjǣrdenlarp May 13 '14 at 19:39
  • 1
    Have you tried explicitly setting it to `Nothing` first? (`Dim myVar As MyClass = Nothing`) – pete May 13 '14 at 19:41

1 Answers1

4

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()
pmcoltrane
  • 3,052
  • 1
  • 24
  • 30