how to initialise an array in c# code example

Example 1: c# initialize array

string[] stringArray = new string[6];
//or
int[] array1 = new int[] { 1, 3, 5, 7, 9 };
//
string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
//etc

Example 2: c# create array

// Define and Initialize
int[] arr = {1, 2, 3};

// Buuuut:
// Initial defining
int[] arr;

// This works
arr = new int[] {1, 2, 3};   

// This will cause an error
// arr = {1, 2, 3};

Example 3: c# how to initialize an array

var array = new int[] { 1, 2, 3 }
var array2 = new ObjectName[] { /* add element to array here */ };

Example 4: C# int array initial values

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.

Example 5: c# create array with n elements

int[] arr = Enumerable.Range(0, X+1).ToArray();