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

Skip to content

System.ArgumentOutOfRangeException F# snippets #7429

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,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="program.fs" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// <Snippet1>
open System

type Guest(fName: string, lName: string, age: int) =
let minimumRequiredAge = 21

do if age < minimumRequiredAge then
raise (ArgumentOutOfRangeException(nameof age, $"All guests must be {minimumRequiredAge}-years-old or older."))

member _.FirstName = fName
member _.LastName = lName
member _.GuestInfo() = $"{fName} {lName}, {age}"

try
let guest1 = Guest("Ben", "Miller", 17);
printfn $"{guest1.GuestInfo()}"
with
| :? ArgumentOutOfRangeException as e ->
printfn $"Error: {e.Message}"
// </Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module BadSearch

// <Snippet6>
open System

module StringSearcher =
let findEquals (s: string) value =
s.Equals(value, StringComparison.InvariantCulture)

let list = ResizeArray<string>()
list.AddRange [ "A"; "B"; "C" ]
// Get the index of the element whose value is "Z".
let index = list.FindIndex(StringSearcher.findEquals "Z")
try
printfn $"Index {index} contains '{list[index]}'"
with
| :? ArgumentOutOfRangeException as e ->
printfn $"{e.Message}"

// The example displays the following output:
// Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
// </Snippet6>

module Example2 =
let test () =
let list = new ResizeArray<string>();
list.AddRange [ "A"; "B"; "C" ]
// <Snippet7>
// Get the index of the element whose value is "Z".
let index = list.FindIndex(StringSearcher.findEquals "Z")
if index >= 0 then
printfn $"'Z' is found at index {list[index]}"
// </Snippet7>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module EmptyString1

// <Snippet15>
open System

let getFirstCharacter (s: string) = s[0]

let words = [ "the"; "today"; "tomorrow"; " "; "" ]
for word in words do
printfn $"First character of '{word}': '{getFirstCharacter word}'"

// The example displays the following output:
// First character of 'the': 't'
// First character of 'today': 't'
// First character of 'tomorrow': 't'
// First character of ' ': ' '
//
// Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
// at <StartupCode$argumentoutofrangeexception>.$EmptyString1.main@()
// </Snippet15>

module StringLib =
// <Snippet16>
let getFirstCharacter (s: string) =
if String.IsNullOrEmpty s then
'\u0000'
else
s[0]
// </Snippet16>
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
module FindWords1

// <Snippet19>

let findWords (s: string) =
let mutable start, end' = 0, 0
let delimiters = [| ' '; '.'; ','; ';'; ':'; '('; ')' |]
let words = ResizeArray<string>()
while end' >= 0 do
end' <- s.IndexOfAny(delimiters, start)
if end' >= 0 then
if end' - start > 0 then
words.Add(s.Substring(start, end' - start))
start <- end' + 1
elif start < s.Length - 1 then
words.Add(s.Substring start)
words.ToArray()

let sentence = "This is a simple, short sentence."
printfn $"Words in '{sentence}':"
for word in findWords sentence do
printfn $" '{word}'"

// The example displays the following output:
// Words in 'This is a simple, short sentence.':
// 'This'
// 'is'
// 'a'
// 'simple'
// 'short'
// 'sentence'
// </Snippet19>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
module NoElements

// <Snippet4>
open System


let list = ResizeArray<string>()
printfn $"Number of items: {list.Count}"
try
printfn $"The first item: '{list[0]}'"
with
| :? ArgumentOutOfRangeException as e ->
printfn $"{e.Message}"

// The example displays the following output:
// Number of items: 0
// Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
// </Snippet4>

module Example2 =
let test () =
let list = ResizeArray<string>()
printfn $"Number of items: {list.Count}"
// <Snippet5>
if list.Count > 0 then
printfn $"The first item: '{list[0]}'"
// </Snippet5>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module NoElements2

// <Snippet13>
let numbers = ResizeArray<int>()
numbers.AddRange [ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 20 ]

let squares = ResizeArray<int>()
for ctr = 0 to numbers.Count - 1 do
squares[ctr] <- int (float numbers[ctr] ** 2)

// The example displays the following output:
// Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
// at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
// at <StartupCode$argumentoutofrangeexception>.$NoElements.main@()
// </Snippet13>

module Correction =
let test () =
let numbers = ResizeArray<int>()
numbers.AddRange [| 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 20 |]
// <Snippet14>
let squares = ResizeArray<int>()
for ctr = 0 to numbers.Count - 1 do
squares.Add(int (float numbers[ctr] ** 2))
// </Snippet14>

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
module NoFind1

// <Snippet17>
let getSecondWord (s: string) =
let pos = s.IndexOf " "
s.Substring(pos).Trim()

let phrases = [ "ocean blue"; "concerned citizen"; "runOnPhrase" ]
for phrase in phrases do
printfn $"Second word is {getSecondWord phrase}"

// The example displays the following output:
// Second word is blue
// Second word is citizen
//
// Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero. (Parameter 'startIndex')
// at System.String.Substring(Int32 startIndex, Int32 length)
// at System.String.Substring(Int32 startIndex)
// at NoFind1.getSecondWord(String s)
// at <StartupCode$argumentoutofrangeexception>.$NoFind1.main@()
// </Snippet17>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module NoFind2

// <Snippet18>
open System

let getSecondWord (s: string) =
let pos = s.IndexOf " "
if pos >= 0 then
s.Substring(pos).Trim()
else
String.Empty

let phrases = [ "ocean blue"; "concerned citizen"; "runOnPhrase" ]
for phrase in phrases do
let word = getSecondWord phrase
if not (String.IsNullOrEmpty word) then
printfn $"Second word is {word}"

// The example displays the following output:
// Second word is blue
// Second word is citizen
// </Snippet18>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
module OOR1
// <Snippet1>
open System

let dimension1 = 10
let dimension2 = -1
try
let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)
printfn "%A" arr
with
| :? ArgumentOutOfRangeException as e ->
if not (isNull e.ActualValue) then
printfn $"{e.ActualValue} is an invalid value for {e.ParamName}: "
printfn $"{e.Message}"

// The example displays the following output:
// Non-negative number required. (Parameter 'length2')
// </Snippet1>

module Example2 =
let makeValid () =
// <Snippet2>
let dimension1 = 10
let dimension2 = 10
let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)
printfn "%A" arr
// </Snippet2>

let validate () =
let dimension1 = 10
let dimension2 = 10
// <Snippet3>
if dimension1 < 0 || dimension2 < 0 then
printfn "Unable to create the array."
printfn "Specify non-negative values for the two dimensions."
else
let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2)
printfn "%A" arr
// </Snippet3>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
module OOR2

// <Snippet8>
open System

let list = ResizeArray<string>()
list.AddRange [ "A"; "B"; "C" ]
try
// Display the elements in the list by index.
for i = 0 to list.Count do
printfn $"Index {i}: {list[i]}"
with
| :? ArgumentOutOfRangeException as e ->
printfn $"{e.Message}"

// The example displays the following output:
// Index 0: A
// Index 1: B
// Index 2: C
// Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
// </Snippet8>

module Example2 =
let test () =
let list = ResizeArray<string>()
list.AddRange [ "A"; "B"; "C" ]
// <Snippet9>
// Display the elements in the list by index.
for i = 0 to list.Count - 1 do
printfn $"Index {i}: {list[i]}"
// </Snippet9>
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
module Race1

// <Snippet11>
open System.Threading

type Continent =
{ Name: string
Population: int
Area: decimal }

let continents = ResizeArray<Continent>()
let mutable msg = ""

let names =
[ "Africa"; "Antarctica"; "Asia"
"Australia"; "Europe"; "North America"
"South America" ]

let populateContinents obj =
let name = string obj
msg <- msg + $"Adding '{name}' to the list.\n"
// Sleep to simulate retrieving data.
Thread.Sleep 50
let continent =
{ Name = name
Population = 0
Area = 0M }
continents.Add continent

// Populate the list.
for name in names do
let th = Thread(ParameterizedThreadStart populateContinents)
th.Start name

printfn $"{msg}\n"

// Display the list.
for i = 0 to names.Length - 1 do
let continent = continents[i]
printfn $"{continent.Name}: Area: {continent.Population}, Population {continent.Area}"

// The example displays output like the following:
// Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
// at System.Collections.Generic.List`1.get_Item(Int32 index)
// at <StartupCode$argumentoutofrangeexception>.$Race1.main@()
// </Snippet11>
Loading