Home
VB.NET
Array.IndexOf, LastIndexOf
Updated Apr 21, 2023
Dot Net Perls
Array.IndexOf. The Array.IndexOf function in VB.NET searches an array from its beginning. It returns the index of the element with the specified value.
LastIndexOf, meanwhile, searches from the end of an array. Both functions return -1 if no match is found. We must test for -1 in an If-Statement.
If
Example. To start, we create an array of 6 elements. Please notice how the array has two elements with value 5—one is at index 2 and one is at index 5.
Then We call the Array.IndexOf Function. It returns the value 2, meaning it found the value 5 at index 2.
Finally We call LastIndexOf. It returns the value 5, meaning it found the value 5 at index 5.
Here We see the difference between IndexOf and LastIndexOf. They locate different elements in some arrays.
Module Module1 Sub Main() Dim arr(5) As Integer arr(0) = 1 arr(1) = 3 arr(2) = 5 arr(3) = 7 arr(4) = 8 arr(5) = 5 ' Search array with IndexOf. Dim index1 As Integer = Array.IndexOf(arr, 5) Console.WriteLine(index1) ' Search with LastIndexOf. Dim index2 As Integer = Array.LastIndexOf(arr, 5) Console.WriteLine(index2) End Sub End Module
2 5
Negative 1. IndexOf and LastIndexOf return -1 if no matching element is found. When using these Functions, you must be careful to check for -1.
Info If you try to use -1 as an index to an array, you will receive an exception.
Module Module1 Sub Main() ' An array. Dim arr() As Integer = {10, 20, 30} ' Search for a value that does not exist. Dim result As Integer = Array.IndexOf(arr, 100) Console.WriteLine(result) End Sub End Module
-1
Usually when using IndexOf functions in .NET, we must use If-Statements and check for negative 1. If a value is guaranteed to be present, this step may not be needed.
String IndexOf
Summary. These Functions are a declarative way to search an array for a specific matching value. When compared to a For-Loop, this reduces code size.
For
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 21, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen