List<T>.GetRange

yechiel Sulzbacher 1 Reputation point
2022-04-04T10:08:23.99+00:00

hi

I was just working with List<T>.GetRange on your online c# compiler and it seems to be inconsistent when I input "list.GetRange(0,list.Count)" I receive the whole list as I should. But when I input " list.GetRange(1,list.Count)" I receive an out of bounds exception which I managed to solve by writing " list.GetRange(1,list.Count-2)" in order to get the range that I want.

Is this an intentional feature or a bug?

thanks for your time

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,094 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 67,921 Reputation points
    2022-04-05T00:52:46.067+00:00

    As designed. Assume the list has 10 elements, with index from 0 to 9

    list.GetRange(0, 10) // returns elements at indexes 0,1,2,3,4,5,6,7,8,9
    list.GetRange(1, 10) // returns elements at indexes 1,2,3,4,5,6,7,8,9,10. List[10] is out of range.

    0 comments No comments

  2. Karen Payne MVP 35,456 Reputation points
    2022-04-05T17:31:15.167+00:00

    See my .NET Fiddle

    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    
    namespace ConsoleApp1
    {
        public class Program
        {
            public static void Main()
            {
                var monthNames = Enumerable.Range(1, 12)
                    .Select((index) => DateTimeFormatInfo.CurrentInfo.GetMonthName(index)).ToList();
    
                Index indexer = new Index(monthNames.FindIndex(item => item.Equals("april", 
                    StringComparison.OrdinalIgnoreCase)));
    
                var fourMonths = monthNames.ByIndex(indexer.Value, 4);
    
                Console.WriteLine(string.Join(",", fourMonths));
    
                Console.WriteLine("");
    
                List<int> list = new() { 1, 2, 3, 4, 5 };
    
                Console.WriteLine($"list[^1] => {list[^1]}");
                Console.WriteLine("");
                var monthNamesArray = Enumerable.Range(1, 12).Select((index) =>
                    DateTimeFormatInfo.CurrentInfo.GetMonthName(index)).ToArray();
    
                Range firstFourRange = ..4;
                Console.WriteLine(string.Join(",", monthNamesArray[firstFourRange]));
            }
        }
    
        static class Extensions
        {
            public static List<T> ByIndex<T>(this List<T> value, int startIndex, int endIndex) => 
                value.GetRange(startIndex, endIndex);
        }
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.