1

I have got following C# code from this link: How to prevent users from typing special characters in textbox

  string allowedchar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  if (!TXT_NewPassword.Text.All(allowedchar.Contains))
  {
   // Not allowed char detected
  }

Following code is vb.net version of above code

    Dim allowedchar As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    If Not TXT_NewPassword.Text.All(allowedchar.Contains) Then
        ' Not allowed char detected
    End If

How can I solve this error? : https://prnt.sc/mzsmkd

Error message:

Overload resolution failed because no accessible 'Contains' accepts this number of arguments

1 Answers1

0

If you're looking for a LINQ solution, I'd use:

Dim allowedchar As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
If Not TXT_NewPassword.Text.All(function(x) allowedchar.contains(x)) Then
    ' Not allowed char detected
End If

String.Contains expects a parameter which is what it will search for. .All loops through each letter in TXT_NewPassword.Text & function(x) allows you to access that letter through x.

ItsPete
  • 2,363
  • 3
  • 27
  • 35
  • Thanks for the correct answer. But why do you think following linked C# code is accepted as solved answer? https://stackoverflow.com/questions/33018299/how-to-prevent-users-from-typing-special-characters-in-textbox –  Mar 19 '19 at 05:11
  • @Markowitz Honestly, I'm not sure. I would have expected to have seen the C# code as `TXT_NewPassword.Text.All(x=>allowedchar.Contains(x))`. – ItsPete Mar 19 '19 at 05:16
  • 1
    The answer is that it is completely valid syntax in C#. There is a long but step-by-step explanation of why it's valid here... https://stackoverflow.com/a/35422304/5198140 – Richardissimo Mar 19 '19 at 06:49
  • 1
    @Markowitz, the translation to VB should have been `If Not TXT_NewPassword.Text.All(AddressOf allowedchar.Contains) Then`. – TnTinMn Mar 19 '19 at 22:07
  • @TnTinMn Thank you. Your code also works. Which one is better your code or ItsPete's code? –  Mar 20 '19 at 06:52
  • 1
    @Markowitz, my previous translation, while closer to the original C# code, is in error and should have been `If Not TXT_NewPassword.Text.All(AddressOf DirectCast(allowedchar, IEnumerable(Of Char)).Contains) Then`. The `String.Contains` method takes a `String` argument. My previous translation and the one in this answer work because VB does an implicit conversion of a `Char` to a `String` . C# does not allow this implicit conversion and as such resolves to the `IEnumerable(Of Char).Contains` method that is implemented by the `String` type. – TnTinMn Mar 20 '19 at 15:08