Dave H
Dave H

Reputation: 653

Optional ByVal boolean parameter is not taking its default value

I am debugging a project right now and it has a function with the following signature:

Public Function changeRemoteDirectory(ByVal newDirectory As String, Optional ByVal Direction As Boolean = True) As Boolean

    MsgBox(direction)

    'rest of code

End Function

I was trying to figure out what was causing this function to return a value of False when I knew that it should return True given the input that I was supplying, so I put MsgBox(direction) into the Function to see what the value of direction was when I called the Function. I called the function like this, yet I received a MsgBox that showed the value of direction to be False:

changeRemoteDirectory("/internal")

The first parameter works just fine and the code that requires it to execute works correctly, but I cannot figure out why Direction has a value of False in a situation where, I believe, it should have its default value of True. I'm not totally opposed to rewriting the Function if need be, but can anybody here discern why Direction does not have a value of True when the function changeRemoteDirectory() is called without the second parameter supplied?

Upvotes: 1

Views: 4532

Answers (1)

jbabey
jbabey

Reputation: 46657

It sounds like you're experiencing one of many pains that optional parameters cause.

When the code that calls changeRemoteDirectory is compiled, the optional parameter is injected into the calls just like a const would be replaced at compile time. Changes to the value of an optional parameter will not take effect without recompiling the caller.

See this article for more info.

In general, you should use method overloads instead of optional parameters. You get all of the same functionality without the pain and performance drawbacks.

Upvotes: 2

Related Questions