2

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?

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
JJS
  • 6,431
  • 1
  • 54
  • 70
  • 2
    You are doing yourself a disservice by turning `Option Strict Off`. – Chris Dunaway Oct 20 '14 at 16:00
  • @ChrisDunaway, I agree with your opinion. This was a purely academic question, and it depends on Option Strict Off. Otherwise you must use row.Field(Of Integer)("number") – JJS Oct 20 '14 at 16:08

1 Answers1

5

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

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • thank you! I fixed my code sample. I should have compiled it before I published. I think a better name is the dictionary access operator, or better yet the default string indexer property operator – JJS Oct 17 '14 at 18:12
  • Matt describes this well. 'x!y' is just a 'shortcut' for 'x("y")' – Dave Doknjas Oct 17 '14 at 18:21