Thanks to visit codestin.com
Credit goes to github.com

Skip to content

System.IndexOutOfRangeException F# snippets #7771

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module Uninit1

// <Snippet10>
let values1 = [| 3; 6; 9; 12; 15; 18; 21 |]
let values2 = Array.zeroCreate<int> 6

// Assign last element of the array to the new array.
values2[values1.Length - 1] <- values1[values1.Length - 1];
// The example displays the following output:
// Unhandled Exception:
// System.IndexOutOfRangeException:
// Index was outside the bounds of the array.
// at <StartupCode$fs>.main@()
// </Snippet10>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module foreach1

// <Snippet7>
open System

let populateArray items maxValue =
let rnd = Random()
[| for i = 0 to items - 1 do
rnd.Next(0, maxValue + 1) |]

// Generate array of random values.
let values = populateArray 5 10
// Display each element in the array.
for value in values do
printf $"{values[value]} "

// The example displays output like the following:
// 6 4 4
// Unhandled Exception: System.IndexOutOfRangeException:
// Index was outside the bounds of the array.
// at <StartupCode$fs>.main@()
// </Snippet7>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module foreach2

// <Snippet8>
open System

let populateArray items maxValue =
let rnd = Random()
[| for i = 0 to items - 1 do
rnd.Next(0, maxValue + 1) |]

// Generate array of random values.
let values = populateArray 5 10
// Display each element in the array.
for value in values do
printf $"{value} "

// The example displays output like the following:
// 10 6 7 5 8
// </Snippet8>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="length1.fs" />
<Compile Include="length2.fs" />
<Compile Include="Uninit1.fs" />
<Compile Include="negative1.fs" />
<Compile Include="negative2.fs" />
<Compile Include="nonzero1.fs" />
<Compile Include="nonzero2.fs" />
<Compile Include="foreach1.fs" />
<Compile Include="foreach2.fs" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module length1

// <Snippet3>
let characters = ResizeArray()
characters.InsertRange(0, [| 'a'; 'b'; 'c'; 'd'; 'e'; 'f' |])

for i = 0 to characters.Count do
printf $"'{characters[i]}' "
// The example displays the following output:
// 'a' 'b' 'c' 'd' 'e' 'f'
// Unhandled Exception:
// System.ArgumentOutOfRangeException:
// Index was out of range. Must be non-negative and less than the size of the collection.
// Parameter name: index
// at <StartupCode$fs>.main@()
// </Snippet3>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module length2

// <Snippet4>
let characters = ResizeArray()
characters.InsertRange(0, [| 'a'; 'b'; 'c'; 'd'; 'e'; 'f' |])

for i = 0 to characters.Count - 1 do
printf $"'{characters[i]}' "
// The example displays the following output:
// 'a' 'b' 'c' 'd' 'e' 'f'
// </Snippet4>
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
module negative1

// <Snippet5>
open System

let numbers = ResizeArray()

let showValues startValue =
// Create a collection with numeric values.
if numbers.Count = 0 then
numbers.AddRange [| 2..2..22 |]

// Get the index of a startValue.
printfn $"Displaying values greater than or equal to {startValue}:"
let startIndex = numbers.IndexOf startValue

// Display all numbers from startIndex on.
for i = startIndex to numbers.Count - 1 do
printf $" {numbers[i]}"

let startValue =
let args = Environment.GetCommandLineArgs()
if args.Length < 2 then
2
else
match Int32.TryParse args[1] with
| true, v -> v
| _ -> 2

showValues startValue

// The example displays the following output if the user supplies
// 7 as a command-line parameter:
// Displaying values greater than or equal to 7:
//
// Unhandled Exception: System.ArgumentOutOfRangeException:
// Index was out of range. Must be non-negative and less than the size of the collection.
// Parameter name: index
// at System.Collections.Generic.List`1.get_Item(Int32 index)
// at Example.ShowValues(Int32 startValue)
// at <StartupCode$fs>.main@()
// </Snippet5>
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
module negative2

// <Snippet6>
open System
open System.Collections.Generic

let numbers = new List<int>()

let showValues startValue =
// Create a collection with numeric values.
if numbers.Count = 0 then
numbers.AddRange [| 2..2..22 |]

// Get the index of startValue.
let startIndex = numbers.IndexOf startValue
if startIndex < 0 then
printfn $"Unable to find {startValue} in the collection."
else
// Display all numbers from startIndex on.
printfn $"Displaying values greater than or equal to {startValue}:"
for i = startIndex to numbers.Count - 1 do
printf $" {numbers[i]}"

let startValue =
let args = Environment.GetCommandLineArgs()
if args.Length < 2 then
2
else
match Int32.TryParse args[1] with
| true, v -> v
| _ -> 2

showValues startValue

// The example displays the following output if the user supplies
// 7 as a command-line parameter:
// Unable to find 7 in the collection.
// </Snippet6>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module nonzero1

// <Snippet1>
open System

let values =
Array.CreateInstance(typeof<int>, [| 10 |], [| 1 |])
let mutable value = 2
// Assign values.
for i = 0 to values.Length - 1 do
values.SetValue(value, i)
value <- value * 2

// Display values.
for i = 0 to values.Length - 1 do
printf $"{values.GetValue i} "

// The example displays the following output:
// Unhandled Exception:
// System.IndexOutOfRangeException: Index was outside the bounds of the array.
// at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)
// at System.Array.SetValue(Object value, Int32 index)
// at <StartupCode$fs>.main@()
// </Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module nonzero2

// <Snippet2>
open System

let values =
Array.CreateInstance(typeof<int>, [| 10 |], [| 1 |])
let mutable value = 2
// Assign values.
for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
values.SetValue(value, i)
value <- value * 2

// Display values.
for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
printf $"{values.GetValue i} "
// The example displays the following output:
// 2 4 8 16 32 64 128 256 512 1024
// </Snippet2>
15 changes: 12 additions & 3 deletions xml/System/IndexOutOfRangeException.xml
Original file line number Diff line number Diff line change
Expand Up @@ -68,28 +68,33 @@
- Forgetting that the upper bound of a collection or a zero-based array is one less than its number of members or elements, as the following example illustrates.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/length1.cs" id="Snippet3":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/length1.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/length1.vb" id="Snippet3":::

To correct the error, you can use code like the following.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/length2.cs" interactive="try-dotnet" id="Snippet4":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/length2.fs" id="Snippet4":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/length2.vb" id="Snippet4":::

Alternately, instead of iterating all the elements in the array by their index, you can use the `foreach` statement (in C#) or the `For Each` statement (in Visual Basic).
Alternately, instead of iterating all the elements in the array by their index, you can use the `foreach` statement (in C#), the `for...in` statement (in F#), or the `For Each` statement (in Visual Basic).

- Attempting to assign an array element to another array that has not been adequately dimensioned and that has fewer elements than the original array. The following example attempts to assign the last element in the `value1` array to the same element in the `value2` array. However, the `value2` array has been incorrectly dimensioned to have six instead of seven elements. As a result, the assignment throws an <xref:System.IndexOutOfRangeException> exception.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/Uninit1.cs" id="Snippet10":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/Uninit1.fs" id="Snippet10":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/Uninit1.vb" id="Snippet10":::

- Using a value returned by a search method to iterate a portion of an array or collection starting at a particular index position. If you forget to check whether the search operation found a match, the runtime throws an <xref:System.IndexOutOfRangeException> exception, as shown in this example.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/negative1.cs" id="Snippet5":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/negative1.fs" id="Snippet5":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/negative1.vb" id="Snippet5":::

In this case, the <xref:System.Collections.Generic.List%601.IndexOf%2A?displayProperty=nameWithType> method returns -1, which is an invalid index value, when it fails to find a match. To correct this error, check the search method's return value before iterating the array, as shown in this example.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/negative2.cs" id="Snippet6":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/negative2.fs" id="Snippet6":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/negative2.vb" id="Snippet6":::

- Trying to use or enumerate a result set, collection, or array returned by a query without testing whether the returned object has any valid data.
Expand Down Expand Up @@ -118,23 +123,27 @@
- Assuming that an array must be zero-based. Arrays that are not zero-based can be created by the <xref:System.Array.CreateInstance%28System.Type%2CSystem.Int32%5B%5D%2CSystem.Int32%5B%5D%29?displayProperty=nameWithType> method and can be returned by COM interop, although they aren't CLS-compliant. The following example illustrates the <xref:System.IndexOutOfRangeException> that is thrown when you try to iterate a non-zero-based array created by the <xref:System.Array.CreateInstance%28System.Type%2CSystem.Int32%5B%5D%2CSystem.Int32%5B%5D%29?displayProperty=nameWithType> method.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/nonzero1.cs" id="Snippet1":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/nonzero1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/nonzero1.vb" id="Snippet1":::

To correct the error, as the following example does, you can call the <xref:System.Array.GetLowerBound%2A> method instead of making assumptions about the starting index of an array.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/nonzero2.cs" interactive="try-dotnet" id="Snippet2":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/nonzero2.fs" id="Snippet2":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/nonzero2.vb" id="Snippet2":::

Note that when you call the <xref:System.Array.GetLowerBound%2A> method to get the starting index of an array, you should also call the <xref:System.Array.GetUpperBound%28System.Int32%29?displayProperty=nameWithType> method to get its ending index.

- Confusing an index and the value at that index in a numeric array or collection. This issue usually occurs when using the `foreach` statement (in C#) or the `For Each` statement (in Visual Basic). The following example illustrates the problem.
- Confusing an index and the value at that index in a numeric array or collection. This issue usually occurs when using the `foreach` statement (in C#), the `for...in` statement (in F#), or the `For Each` statement (in Visual Basic). The following example illustrates the problem.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/foreach1.cs" id="Snippet7":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/foreach1.fs" id="Snippet7":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/foreach1.vb" id="Snippet7":::

The iteration construct returns each value in an array or collection, not its index. To eliminate the exception, use this code.

:::code language="csharp" source="~/snippets/csharp/System/IndexOutOfRangeException/Overview/foreach2.cs" interactive="try-dotnet" id="Snippet8":::
:::code language="fsharp" source="~/snippets/fsharp/System/IndexOutOfRangeException/Overview/foreach2.fs" id="Snippet8":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.indexoutofrangeexception/vb/foreach2.vb" id="Snippet8":::

- Providing an invalid column name to the <xref:System.Data.DataView.Sort%2A?displayProperty=nameWithType> property.
Expand All @@ -143,7 +152,7 @@

Using hard-coded index values to manipulate an array is likely to throw an exception if the index value is incorrect or invalid, or if the size of the array being manipulation is unexpected. To prevent an operation from throwing an <xref:System.IndexOutOfRangeException> exception, you can do the following:

- Iterate the elements of the array using the [foreach](/dotnet/csharp/language-reference/keywords/foreach-in) statement (in C#) or the [For Each...Next](/dotnet/visual-basic/language-reference/statements/for-each-next-statement) construct (in Visual Basic) instead of iterating elements by index.
- Iterate the elements of the array using the [foreach](/dotnet/csharp/language-reference/keywords/foreach-in) statement (in C#), the [for...in](/dotnet/fsharp/language-reference/loops-for-in-expression) statement (in F#), or the [For Each...Next](/dotnet/visual-basic/language-reference/statements/for-each-next-statement) construct (in Visual Basic) instead of iterating elements by index.

- Iterate the elements by index starting with the index returned by the <xref:System.Array.GetLowerBound%2A?displayProperty=nameWithType> method and ending with the index returned by the <xref:System.Array.GetUpperBound%2A?displayProperty=nameWithType> method.

Expand Down