Search code examples
vb.netoption-strict

Option Strict On disallows implicit conversions from 'String ' to 'Char' VB.NET


I'm using Option Strict On (and sometimes wishing I wasn't!) but have a piece of code that works as I want it to without it but not with it.

It should be quite simple I think but I couldn't find an answer here.

My code that works with Option Strict Off is this:

If returnedString.Contains(".exe ") And returnvalues.Count = 0 Then
  Dim x As Integer = 0
  For Each entry In returnedString.Split(".exe ")
    If (entry.Length > 0) And x = 0 Then
      returnvalues.Add(entry & ".exe")
      x = x + 1
    End If
  Next
End If

The returnedString is, for example:

C:\Program Files (x86)\Whatever\Whatever.exe

and

C:\Program Files (x86)\Whatever\Whatever

is returned in entry if Option Strict is off, which is what I want.

However, if I use Visual Studio's suggestion of adding a cast, the following does not work:

For Each entry As String In returnedString.Split(CType(".exe ", Char()))

The first entry returned is C:\Program and this is presumably because it finds the Char ' '; I don't want it to check per character, I want it to check the whole string like it does when Option Strict is off but I can't work it out.

I tried .ToCharArray but that really does the same thing.


Solution

  • Please continue to use Option Strict On. It is annoying but it will save your day a lot.

    For your problem:

    It is caused by the fact that when you enable Option Strict On, the compiler is no longer allowed to take the first char from your string and use it as separator. Because there is no overload for string.Split that takes just a string, then it complains about an attempt to do an invalid conversion.

    If you want to use a string as separator then it is required to pass an array of strings as the first parameter, and a second parameter of type StringSplitOptions is required.

    Fixing it is really simple. Just change the line to:

    For Each entry In returnedString.Split({".exe"}, StringSplitOptions.None)