Optional param detection?

rmatthew

Well-known member
Joined
Dec 30, 2002
Messages
115
Location
Texas
Ack - seems I am always in here admiting I dont know something :)

In any case is there a way to see if an optional paramater was included in the original call to a function or sub?

Thanks
 
You shouldnt be using Optional parameters anyway. You should
overload the sub.

Code:
Private Sub SomeFunction(param As String)
  msgBox param & " was passed!"
End Sub

Private Sub SomeFunction()
  MsgBox "Nothing was passed."
End Sub
 
To add what VolteFace said (thanks, btw, didnt know VB.NET supported overloads):

You can mimic your own custom optional by moving all of your "real" code into the function that takes the params. For example:
Code:
Private Sub SomeFunction()
    Console.WriteLine("Nothing passed")
    SomeFunction(String.Empty)
End Sub

Private Sub SomeFunction(param As String)
     Can you use + in VB.NET or is that C# only?
     You might need to use &
    Console.WriteLine("Passed: " + param)
End Sub

This is handy in a lot of cases where you want to use an optional parameter but you dont want to be VB.NET specific. In the example above, the param isnt really optional, but you CAN call it as:
SomeFunction()
or
SomeFunction("Test")

-Nerseus
 
If I remember right, the compiled code that gets created is basically creating overloads for all of your optional arguments. You get more control with your own overloads and, I think, theyre easier to use. You only have to code the overload once and hopefully you dont have TOO many optional params. If you have more than a couple of optionals you may be trying to punch too much bang for the buck into one function OR you probably end up only using 3 or 4 "versions" of the function (meaning, which params are passed and which are left "optional").

And, dont be surprised if VB.NET version 3 cuts out the optionals :)

-Nerseus
 
Nerseus, in VB.NET you can use either + or & to concatenate
strings, but it is much better if you use & only for concatenation.
Plus, if youre doing a LOT of concatenating, use a StringBuilder
class, instead. :)

Save the + operator for addition.

[edit]
Also, relating back to the thread subject... I never use optional
parameters; I always overload the methods. It helps organize
things, and the IntelliSense is nicer, too. :)
[/edit]
 
No, the compiled code doesnt create overloads. The .NET framework itself DOES support optional parameters, and it gets compiled just fine. It is C# itself that doesnt support optional parameters.
 
Back
Top