0

I have a program where the user inputs a string. This strings length is always a multiple of 8.

So to convert the string I split the string every 8 characters into an array.

I do that with this code

Dim substrings = Enumerable.Range(0, input.Length \ 8).[Select](Function(i) input.Substring(i * 8, 8))

That works fine.

I can then type String.Join(" ", substrings) and it works like it should, it takes whatever the user entered and puts a space between every 8 characters.

However, if I try to do this:

Dim indexOfEntry
For Each e In substrings
    indexOfEntry = Array.IndexOf(substrings, e)
Next

I get an error:

An unhandled exception of type 'System.InvalidCastException' occurred in DataCalculator.exe

Additional information: Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Int32,System.String]' to type 'System.Array'.

How can I fix this?

1
  • Instead of a For Each, could you just do For indexOfEntry As Integer = 0 To substrings.Length-1 ? Commented Jul 29, 2014 at 15:04

2 Answers 2

1

Change the splitting line to return an array of strings

 Dim substrings = Enumerable.Range(0, input.Length \ 8).[Select](Function(i) _ 
                                   input.Substring(i * 8, 8)).ToArray()

I really advice you to turn ON the OPTION STRICT flag in your VB.NET configuration.
This allows the compiler to examine your code for potential pitfalls like this.

The automatic conversions of values like it was in the VB6 time should not have a place in NET world (but this is an opinion and I reckon that porting of old programs is easier with that flag set to OFF.)

Sign up to request clarification or add additional context in comments.

3 Comments

Turning option strict on gave my program 102 new errors. I have a lot of work ahead of me if I want to fix these.
Yeah, that would be AT LEAST 102 new errors... lol. In that situation, I would advise turning Option Strict On by using that line at the top of each module/class/file. Then you can go through them one at a time.
Yes it is a sad story. However, follow the advice of @Grim and fix your code piece by piece. It will be better
0

Your substrings variable isn't an Array; it's an IEnumerable(Of String). You could convert it to an array with substrings.ToArray().

Turning Option Strict On will catch errors like this at compile-time. In this case, you would see an "Overload resolution failed..." on the Array.IndexOf call, which would hint that the variable is not an array variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.