Home > database >  How to use named tuples as optional parameters?
How to use named tuples as optional parameters?

Time:10-18

Here is a code sample:

Sub Main()
    Dim t As (t1 As String, t2 As String)
    t.t1 = "123"
    t.t2 = "456"

    TupleTest(t)
End Sub

' line below produces Constant Expression Required error for the default parameters
Sub TupleTest(Optional t As (t1 As String, t2 As String) = ("", ""))

End Sub

I've also tried replacing ("", "") with (String.Empty, String.Empty) and (Nothing, Nothing), but I get the same error.

So is it possible to have a named tuple as an optional parameter?

P.S. This is .NET 4.6.1.

CodePudding user response:

Use Nothing to initialize the optional parameter. That will evaluate to the default value of the structure. Then, use .Equals to check the equality of the argument:

Sub TupleTest(Optional t As (t1 As String, t2 As String) = Nothing)
    If t.Equals((Nothing, Nothing)) Then
        ' Do something
    End If

End Sub

Note that this is the same as with many of the existing built-in .NET structures. For example, Point, Size, Color, Rectangle, etc., but all of those have a self-referencing Shared property, which allows us to do something like this:

Sub Test(Optional p As Point = Nothing)
    If p = Point.Empty Then
        ' Do something
    End If
End Sub

ValueTuples, on the other hand, don't have an Empty property and don't implement the equality operator. That's why we have to go with the slightly awkward .Equals((Nothing, Nothing)).

  • Related