C# Array initialization - with non-default value

前端 未结 6 1839
温柔的废话
温柔的废话 2020-12-08 20:03

What is the slickest way to initialize an array of dynamic size in C# that you know of?

This is the best I could come up with

private bool[] GetPageN         


        
6条回答
  •  情话喂你
    2020-12-08 20:12

    EDIT: as a commenter pointed out, my original implementation didn't work. This version works but is rather un-slick being based around a for loop.

    If you're willing to create an extension method, you could try this

    public static T[] SetAllValues(this T[] array, T value) where T : struct
    {
        for (int i = 0; i < array.Length; i++)
            array[i] = value;
    
        return array;
    }
    

    and then invoke it like this

    bool[] tenTrueBoolsInAnArray = new bool[10].SetAllValues(true);
    

    As an alternative, if you're happy with having a class hanging around, you could try something like this

    public static class ArrayOf
    {
        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 invoke like

    bool[] tenTrueBoolsInAnArray = ArrayOf.Create(10, true);
    

    Not sure which I prefer, although I do lurv extension methods lots and lots in general.

提交回复
热议问题