ArgumentOutOfRangeException in C# with Examples

  By : Suresh Dasari
  Posted On : 30-May-2023

Here we will learn what is argumentoutofrangeexception in c#, how to handle or avoid argumentoutofrangeexception in c#, and how to fix argumentoutofrangeexception in c# with examples.

What is ArgumentOutOfRangeException in C#?

In c#, ArgumentOutOfRangeException is an exception that will occur when the value of an argument falls outside the allowable range of values defined by the invoke method.

 

In application, when we get an ArgumentOutOfRangeExpcetion it indicates that the value of the method argument is not within the acceptable range that could result a runtime error (System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.') as shown below.

 

ArgumentOutOfRange Exception in C#

Possible Ways to Get ArgumentOutOfRangeException in C#

Following are some possible ways of getting the ArgumentOutOfRangeException error in c#.

 

Example1: When you try to access the list elements using an index value more than its valid range.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         List lst = new List { 100, 200, 300};
         Console.WriteLine(lst[3]); // Throws ArgumentOutOfRangeException
         Console.ReadLine();
      }
   }
}

In this example, lst list contains a total of 3 elements which means we can access the list elements using a valid range of 0 to 2. Here, we are trying to access the 4th element of the list using lst[3] which is outside of the valid range due to that we will get System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')'.

 

Example2: When you try to loop through the collection items using index value more than its total elements.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      { 
         List lst = new List { 10, 20, 30, 40 };
         for (int i = 0; i <= lst.Count; i++)
         {
            Console.WriteLine(lst[i]); // Throws ArgumentOutOfRangeException
         }
         Console.ReadLine();
      }
   }
}

In this example, we are looping through the lst list using items count with condition <= instead of < which is one element beyond the valid range due to that we will get System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.'.

 

Example3: When you try to change the string based on the substring position, and you failed to determine whether the substring was found or not.

 

using System;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         string[] names = { "Suresh Dasari", "Rohini Alavala", "Trishika" };
         foreach (var name in names)
         {
            Console.WriteLine("{0}", GetSurName(name));
         }
         Console.ReadLine();
      }
      static string GetSurName(string name)
      {
         int pos = name.IndexOf(" ");
         return name.Substring(pos).Trim();
      }
   }
}

In this example, we used the string IndexOf method to find the position of the substring that contains space. By using that position, we are getting the second word using the substring method from the specified string. In case the string does not contain space, it will return empty in that case we will get the ArgumentOutOfRangeException exception as we are not checking whether the GetSurName method returning the value or not.

How to Handle ArgumentOutOfRangeException in C#

In c#, we have many ways to handle or prevent the “ArgumentOutOfRangeException” error.

 

Solution1: To access elements from collection objects, the index will start from 0 so while accessing the elements we need to make sure that the upper bound of the collection is one less than the total number of elements.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         List lst = new List { 10, 20, 30, 40 };
         for (int i = 0; i < lst.Count; i++)
         {
            Console.WriteLine(lst[i]);
         }
         Console.ReadLine();
      }
   }
}

In this example, we are looping through the lst list using list items count with condition < which is one element less than the total elements. This will prevent ArgumentOutOfRange Exception from the application.

 

Solution2: If you use for loop in c#, you need to consider using the index of the collection to loop through the elements. Instead, use foreach loop to avoid the index dependency and directly access the elements.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      {
         List lsts = new List { 10, 20, 30, 40 };
         foreach (var lst in lsts)
         {
            Console.WriteLine(lst);
         }
         Console.ReadLine();
      }
   }
}

In this example, we used a foreach loop to loop through the lst list without worrying about the index of elements in lst array and it will prevent ArgumentOutOfRange Exception.

 

Solution3: To prevent ArgumentOutOfRangeException, you need to verify whether the value returned by the method is valid or not before performing any other operations.

 

using System;

namespace Tutlane
{
   class Program
   {
      static void Main(string[] args)
      { 
         string[] names = { "Suresh Dasari", "Rohini Alavala", "Trishika" };
         foreach (var name in names)
         {
            string sName = GetSurName(name);
            if (!string.IsNullOrEmpty(sName))
            Console.WriteLine("{0}", sName);
         }
         Console.ReadLine();
      }
      static string GetSurName(string name)
      {
         int pos = name.IndexOf(" ");
         if(pos > 0)
         {
            return name.Substring(pos).Trim();
         }
         else
         {
            return string.Empty;
         }
      }
   }
}

In this example, we are validating whether the value that is returned by the GetSurName method is valid or not before performing any other operations so it will automatically fix the ArgumentOutOfRangeException. 

 

These are the few scenarios in which we will encounter ArgumentOutOfRangeException, there are other scenarios also where we will get this exception so we need to make sure that we will validate the data before performing any other operations.