yechiel Sulzbacher 1 Reputation point


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

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.
9,470 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce ( 48,711 Reputation points

    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 34,591 Reputation points

    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", 
                var fourMonths = monthNames.ByIndex(indexer.Value, 4);
                Console.WriteLine(string.Join(",", fourMonths));
                List<int> list = new() { 1, 2, 3, 4, 5 };
                Console.WriteLine($"list[^1] => {list[^1]}");
                var monthNamesArray = Enumerable.Range(1, 12).Select((index) =>
                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