csharp initialize array
Code Example - csharp 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
csharp 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};
csharp 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.
csharp how to initialize an array
var array = new int[] { 1, 2, 3 }
var array2 = new ObjectName[] { /* add element to array here */ };
csharp string array initialization
string[] items = { "Item1", "Item2", "Item3", "Item4" };
string[] items = new string[]
{
"Item1", "Item2", "Item3", "Item4"
};
string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...
csharp how to write an array in a single line
// How to display an array on the same line:
string[] names = {"name1", "name2", "name3"}
Console.WriteLine("{0}", string.Join(", ", names));
csharp define array
float[] floats = new float[]{1.0,1.1,1.4,1.23,2212.233};
array declaration in csharp
// Syntax: data_type[] variable_name = new data_type[size];
// Decalring array of integers of length 5
int[] intArr = new int[5];
// Declaring array of strings of length 5
string[] names = new string[5];
// We can also populate the array, if we know the elements in advance
int[] evenDigits = new int[] {0,2,4,6,8}; // notice that in this, we don't need explicit size declaration.
csharp int array
int[,] array = new int[4, 2];
int[,] array2D_1 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
int[,] array2D_2 = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
int[,,] array3D = new int[2, 3, 4] {
{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } },
{ { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, { 21, 22, 23, 24 } }
};
// array2D_1[0,1] = 2
// array2D_2[1,0] = 3
// array3D[1,2,3] = 24
csharp initialize array of objects
Object[] objArray = new Object[] {new Object(), ... , new Object()};