Skip to content
AgileLogics
4 min read

Tuples and Anonymous Types

Prerequisites: Subs and functions

Tuples

A tuple groups a few values without declaring a class — handy for returning more than one result:

Module Program
    Function MinMax(values As Integer()) As (Min As Integer, Max As Integer)
        Return (values.Min(), values.Max())
    End Function

    Function Divide(a As Integer, b As Integer) As (Quotient As Integer, Remainder As Integer)
        Return (a \ b, a Mod b)
    End Function

    Sub Main()
        Dim result = MinMax({4, 9, 1, 7})
        Console.WriteLine($"{result.Min}..{result.Max}")

        Dim d = Divide(17, 5)
        Console.WriteLine($"{d.Quotient} remainder {d.Remainder}")

        Dim point = (X:=3, Y:=4)
        Console.WriteLine(point)
        Console.WriteLine(point.Equals((3, 4)))
    End Sub
End Module
1..9
3 remainder 2
(3, 4)
True
  • (Min As Integer, Max As Integer) declares a tuple type with named elements; (X:=3, Y:=4) creates one.
  • Tuples are value types; Equals compares them element by element.
  • Use tuples for small, local groupings; when a group of values is used widely, give it a proper class or structure.

Anonymous types

An anonymous type is a quick read-only object, created with New With { ... } — mostly used in LINQ queries:

Module Program
    Sub Main()
        Dim p = New With {Key .Name = "Ada", .Age = 36}
        Console.WriteLine(p.Name & " " & p.Age)
        Console.WriteLine(p)

        Dim words = {"kiwi", "banana", "fig"}
        Dim info = From w In words
                   Order By w.Length
                   Select New With {.Word = w, .Length = w.Length}

        For Each i In info
            Console.WriteLine($"{i.Word}: {i.Length}")
        Next
    End Sub
End Module
Ada 36
{ Name = Ada, Age = 36 }
fig: 3
kiwi: 4
banana: 6

In VB, anonymous type properties are mutable unless marked Key; Key properties are read-only and are used for equality. In query syntax, Select w, w.Length creates an anonymous type automatically.

The With block

Unrelated to New With, a With block saves repeating an object name:

Public Class Settings
    Public Property Theme As String
    Public Property FontSize As Integer
    Public Property AutoSave As Boolean
End Class

Module Program
    Sub Main()
        Dim s As New Settings()
        With s
            .Theme = "dark"
            .FontSize = 14
            .AutoSave = True
        End With
        Console.WriteLine($"{s.Theme} {s.FontSize} {s.AutoSave}")
    End Sub
End Module
dark 14 True