1
0
mirror of https://github.com/oliverbooth/X10D synced 2024-11-22 19:48:46 +00:00

Add Array.Fill

This commit is contained in:
Oliver Booth 2022-04-20 19:27:06 +01:00
parent e183c31579
commit 85becd2415
No known key found for this signature in database
GPG Key ID: 32A00B35503AF634
2 changed files with 69 additions and 3 deletions

View File

@ -15,8 +15,7 @@ public class ArrayTests
args.Clear();
int[] comparison = Enumerable.Repeat(0, args.Length).ToArray();
CollectionAssert.AreEqual(args, comparison, $"{string.Join(", ", args)} is not equal to" +
$"{string.Join(", ", comparison)}. ");
CollectionAssert.AreEqual(args, comparison);
}
[TestMethod]
@ -25,4 +24,24 @@ public class ArrayTests
int[]? array = null;
Assert.ThrowsException<ArgumentNullException>(array!.Clear);
}
[TestMethod]
[DataRow]
[DataRow(1)]
[DataRow(1, 2, 3)]
[DataRow(1, 2, 3, 4, 5)]
public void Fill(params int[] args)
{
args.Fill(1);
int[] comparison = Enumerable.Repeat(1, args.Length).ToArray();
CollectionAssert.AreEqual(args, comparison);
}
[TestMethod]
public void FillNull()
{
int[]? array = null;
Assert.ThrowsException<ArgumentNullException>(() => array!.Fill(0));
}
}

View File

@ -53,7 +53,7 @@ public static class ArrayExtensions
{
end = array.Length - end;
}
array.Clear(index, end - index);
}
@ -86,4 +86,51 @@ public static class ArrayExtensions
Array.Clear(array, index, length);
}
/// <summary>
/// Assigns the given value to each element of the array.
/// </summary>
/// <param name="array">The array to be filled.</param>
/// <param name="value">The value to assign to each array element.</param>
/// <typeparam name="T">The type of the elements in the array.</typeparam>
/// <exception cref="ArgumentNullException"><paramref name="array" /> is <see langword="null" />.</exception>
public static void Fill<T>(this T?[] array, T value)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Length == 0)
{
return;
}
Array.Fill(array, value);
}
/// <summary>
/// Assigns the given value to the elements of the array which are within the range of <paramref name="startIndex" />
/// (inclusive) and the next <paramref name="count" /> number of indices.
/// </summary>
/// <param name="array">The array to be filled.</param>
/// <param name="value">The value to assign to each array element.</param>
/// <param name="startIndex">A 32-bit integer that represents the index in the array at which filling begins.</param>
/// <param name="count">The number of elements to fill.</param>
/// <typeparam name="T">The type of the elements in the array.</typeparam>
/// <exception cref="ArgumentNullException"><paramref name="array" /> is <see langword="null" />.</exception>
public static void Fill<T>(this T?[] array, T value, int startIndex, int count)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (count == 0 || array.Length == 0)
{
return;
}
Array.Fill(array, value, startIndex, count);
}
}