All possible array initialization syntaxes

2018-12-31 04:09发布

What are all the array initialization syntaxes that are possible with C#?

13条回答
不流泪的眼
2楼-- · 2018-12-31 05:00

In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:

var array = Enumerable.Repeat(string.Empty, 37).ToArray();

Also please take part in this discussion.

查看更多
墨雨无痕
3楼-- · 2018-12-31 05:01

Example to create an array of a custom class

Below is the class definition.

public class DummyUser
{
    public string email { get; set; }
    public string language { get; set; }
}

This is how you can initialize the array:

private DummyUser[] arrDummyUser = new DummyUser[]
{
    new DummyUser{
       email = "abc.xyz@email.com",
       language = "English"
    },
    new DummyUser{
       email = "def@email.com",
       language = "Spanish"
    }
};
查看更多
初与友歌
4楼-- · 2018-12-31 05:01
int[] array = new int[4]; 
array[0] = 10;
array[1] = 20;
array[2] = 30;

or

string[] week = new string[] {"Sunday","Monday","Tuesday"};

or

string[] array = { "Sunday" , "Monday" };

and in multi dimensional array

    Dim i, j As Integer
    Dim strArr(1, 2) As String

    strArr(0, 0) = "First (0,0)"
    strArr(0, 1) = "Second (0,1)"

    strArr(1, 0) = "Third (1,0)"
    strArr(1, 1) = "Fourth (1,1)"
查看更多
永恒的永恒
5楼-- · 2018-12-31 05:04
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
查看更多
牵手、夕阳
6楼-- · 2018-12-31 05:05
Enumerable.Repeat(String.Empty, count).ToArray()

Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.

查看更多
浮光初槿花落
7楼-- · 2018-12-31 05:05

Repeat without LINQ:

float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
查看更多
登录 后发表回答