Optional param detection?

rmatthew

Centurion
Joined
Dec 30, 2002
Messages
115
Location
Texas
Ack - seems I am always in here admiting I don't 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 shouldn't be using Optional parameters anyway. You should
overload the sub.

Visual Basic:
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, didn't 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:
Visual Basic:
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 don't want to be VB.NET specific. In the example above, the param isn't 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, they're easier to use. You only have to code the overload once and hopefully you don't 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, don't 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 you're 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 doesn't create overloads. The .NET framework itself DOES support optional parameters, and it gets compiled just fine. It is C# itself that doesn't support optional parameters.
 
Back
Top