Search code examples
.netvb.netlinqoperatorslinq-to-dataset

Where can I get information on the ! operator used by VB.Net in Linq to DataSet?


The Sample Queries application uses a ! operator to reference a field in the DataRow.

Option Strict Off

Imports System.Data
Imports System.Linq

Module Program

    Public Sub Main()
        Dim numbers() As Integer = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
        Dim table As New DataTable("Numbers")
        table.Columns.Add("number", GetType(Integer))
        For Each n In numbers
            table.Rows.Add(New Object() {n})
        Next

        Dim lowNums = From row In table.Rows _
                      Where row!number < 5
                      Select row

        For Each x In lowNums
            Console.WriteLine(x!number)
        Next
    End Sub

End Module

What is the ! operator called? Where are the rules documented?


Solution

  • This is (in this context) the Exclamation point Operator:

    "Use the ! operator only on a class or interface as a dictionary access operator. The class or interface must have a default property that accepts a single String argument. The identifier immediately following the ! operator becomes the argument value passed to the default property as a string."

    so the code row!number is equivalent to row("number")

    This operator is a legacy carryover from VB6 and should be avoided in VB.NET IMO. It is not really related to LINQ specifically.

    Your example is a little contrived as it doesn't compile (even with Option Strict Off) - Edit: this has now been amended but still won't compile with Option Strict Off

    note "The ! character is also used as the Single type character." e.g. Dim s! = 0.12 but that is not the intention of the code in your context