Search code examples
.netvb.netlinqoption-infer

Can be LINQ rewritten to avoid MissingMemberException with 'Option Infer Off'?


This is simple encoder of string into a literal which is acceptable in regex. Works well with Option Infer On, but crashes in rumtime with Option Infer Off, producing MissingMemberException: No default member found for type VB$AnonymousDelegate_1(Of Char, String).

Can the LINQ expression be rewritten to work even with Option Infer Off? I would like to keep it off because I think there is a risk turning Option Infer On in a large legacy project/library. (Or am I wrong?)

This is the code of the method:

Shared Function EscapeLiteralForRegexPattern(inputString As String) As String

  '*** Based on Escape(). Keep them in sync.
  Const dontEscapeFrom = &H20
  Const dontEscapeTo = &H7E
  If String.IsNullOrEmpty(inputString) Then Return inputString

  Const escaper As String = "\"
  Const escapePattern As String = escaper & escaper
  Const tabPattern As String = escaper & "t"
  Const crPattern As String = escaper & "r"
  Const lfPattern As String = escaper & "n"
  Const unicodePattern As String = escaper & "u{0:X4}"
  Const asciiPattern As String = escaper & "x{0:X2}"

  Dim ConvertChar = Function(c As Char) As String
             If c = escaper Then Return escapePattern
             Dim ac As Integer = AscW(c)
             If ac >= dontEscapeFrom AndAlso ac <= dontEscapeTo Then
               Return Regex.Escape(c)
             End If
             Dim result As String = String.Format(If(ac < &H80, asciiPattern, unicodePattern), ac)
             If dontEscapeFrom = 0 Then Return result
             Select Case c
               Case vbTab
                 Return tabPattern
               Case vbCr
                 Return crPattern
               Case vbLf
                 Return lfPattern
               Case Else
                 Return result
             End Select
           End Function

  Return String.Join(String.Empty, inputString.Select(Function(c) ConvertChar(c)).ToArray())

End Function

This is LINQ change I tried (but the problem remained):

  Return String.Join(String.Empty, inputString.Select(Function(c As Char) As String
                              Return ConvertChar(c)
                            End Function).ToArray())

Solution

  • Credit goes to Hans Passant – see his comment.

    I was adding the code into legacy bulky library which needs to have Option Explicit Off, Option Strict Off until rewritten.

    I forgot they are off and therefore missed some explicit type declarations during coding. After Option Explicit On and Option Strict On and all requested corrections, the entire problem with MissingMemberException went away.