EDIT: as the commentator noted, my initial implementation did not work. This version works, but rather nonsmooth, based on the for loop.
If you want to create an extension method, you can try this
public static T[] SetAllValues<T>(this T[] array, T value) where T : struct { for (int i = 0; i < array.Length; i++) array[i] = value; return array; }
and then call it like this:
bool[] tenTrueBoolsInAnArray = new bool[10].SetAllValues(true);
Alternatively, if you are happy that the class is hanging around, you can try something like this
public static class ArrayOf<T> { public static T[] Create(int size, T initialValue) { T[] array = (T[])Array.CreateInstance(typeof(T), size); for (int i = 0; i < array.Length; i++) array[i] = initialValue; return array; } }
which you can call as
bool[] tenTrueBoolsInAnArray = ArrayOf<bool>.Create(10, true);
Not sure what I prefer, although I use lurv extension methods many and many in general.
Neil Hewitt Sep 26 '08 at 0:46 2008-09-26 00:46
source share