Gowtama Krishna Gowtama Krishna - 3 months ago 13
Vb.net Question

Default value to a optional class variable parameter function call in vb.net

I am trying to pass a class variable as an optional parameter to a function. But it requires a default value. What could I set the default value for the optional class variable.

Private Function SaveFruit(Optional byval tempBanana As BananaClass = ?)

Answer

Reference types' default value is Nothing (the null reference).

Private Function SaveFruit(Optional byval tempBanana As BananaClass = Nothing)
    If tempBanana Is Nothing Then tempBanana = OtherDefaultBanana
    .....
End Function

As shown in the example above you have to check if it's Nothing with the Is-operator before you can use it, otherwise you will get a NullReferenceException. Then you can either assign another instance which already exists or one that you initialize now.