diff --git a/src/Libraries/CoreNodes/List.cs b/src/Libraries/CoreNodes/List.cs index 0288c0b7e03..4833971c456 100644 --- a/src/Libraries/CoreNodes/List.cs +++ b/src/Libraries/CoreNodes/List.cs @@ -625,6 +625,16 @@ public static IList ShiftIndices(IList list, int amount) [IsVisibleInDynamoLibrary(true)] public static object GetItemAtIndex(IList list, int index) { + if (index<0) + { + index = list.Count + index; + } + + // When calculated index is more than list count or still negative, throw exception + if (index >= list.Count || index < 0) + { + throw new IndexOutOfRangeException(); + } return list[index]; } diff --git a/test/Libraries/CoreNodesTests/ListTests.cs b/test/Libraries/CoreNodesTests/ListTests.cs index 59e2c24bbf0..14c2fbd110e 100644 --- a/test/Libraries/CoreNodesTests/ListTests.cs +++ b/test/Libraries/CoreNodesTests/ListTests.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using Dynamo.Graph.Nodes; using NUnit.Framework; using List = DSCore.List; @@ -500,6 +501,35 @@ public static void GetFromList() Assert.AreEqual(2, List.GetItemAtIndex(new List { 0, 1, 2, 3 }, 2)); } + [Test] + [Category("UnitTests")] + public static void GetNegtiveIndexItemFromList() + { + Assert.AreEqual(3, List.GetItemAtIndex(new List { 0, 1, 2, 3 }, -1)); + } + + [Test] + [Category("UnitTests")] + public static void GetNegtiveIndexItemFromListCouldThrow() + { + Assert.Throws(() => + { + // -7 as index argument will cause exception. + List.GetItemAtIndex(new List { 0, 1, 2, 3 }, -7); + }); + } + + [Test] + [Category("UnitTests")] + public static void GetPositiveIndexItemFromListCouldThrow() + { + Assert.Throws(() => + { + // 7 as index argument will cause exception. + List.GetItemAtIndex(new List { 0, 1, 2, 3 }, 7); + }); + } + [Test] [Category("UnitTests")] public static void TakeListSlice()