initialize an array in csharp

In C#, arrays can be initialized in several ways depending on the requirements of the program. Here are a few examples of initializing arrays in C#:

  1. Initializing arrays with the new keyword and size:
main.cs
int[] numbers = new int[5];
28 chars
2 lines

This example initializes an integer array of size 5 with default values (0 in this case).

  1. Initializing arrays with values:
main.cs
int[] numbers = new int[] {1, 2, 3, 4, 5};
43 chars
2 lines

This example initializes an integer array with values 1 to 5.

  1. Shorter syntax for initializing arrays with values:
main.cs
int[] numbers = {1, 2, 3, 4, 5};
33 chars
2 lines

This example is a shorter version of the previous example, but can only be used for array initialization.

  1. Initializing arrays with default values:
main.cs
bool[] booleanArray = new bool[3]; // initializes to false
string[] stringArray = new string[3]; // initializes to null
120 chars
3 lines

This initializes a boolean array with default values of false and a string array with default values of null.

  1. Initializing arrays with initialization expressions:
main.cs
int[] evenNumbers = new int[5] {2, 4, 6, 8, 10};
49 chars
2 lines

This initializes an integer array of size 5 with even numbers using an initialization expression.

These are just a few examples of how arrays can be initialized in C#. An array can also be initialized using other data types, such as strings, characters or objects.

gistlibby LogSnag