Sunday, 2 April 2023

Array in C#

In C#, an array is a collection of elements of the same data type stored in a contiguous block of memory. It is declared using square brackets [] and can hold a fixed number of elements.

Here is an example of how to declare and initialize an array of integers:

csharp
int[] myArray = new int[5]; // creates an array of 5 integers // initialize the array myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; myArray[3] = 4; myArray[4] = 5;

Alternatively, you can also initialize the array elements while declaring the array:

csharp
int[] myArray = { 1, 2, 3, 4, 5 };

You can access the elements of an array using the index of the element in the array, starting from 0. For example, to access the first element of the array:

csharp
int firstElement = myArray[0];

Arrays can also be multidimensional. For example, here is how to declare and initialize a 2-dimensional array:

csharp
int[,] my2DArray = new int[2, 3]; // creates a 2x3 array // initialize the array my2DArray[0, 0] = 1; my2DArray[0, 1] = 2; my2DArray[0, 2] = 3; my2DArray[1, 0] = 4; my2DArray[1, 1] = 5; my2DArray[1, 2] = 6;

To access an element in a 2-dimensional array, you need to provide both the row and column index:

csharp

int element = my2DArray[1, 2]; // gets the element in row 1, column 2 (which is 6) 




Sure, here's some more information about arrays in C#:

  1. Array length: You can get the length of an array using the Length property. For example:
csharp
int[] myArray = { 1, 2, 3, 4, 5 }; int length = myArray.Length; // length is 5
  1. Foreach loop: You can use a foreach loop to iterate over the elements of an array. For example:
csharp
int[] myArray = { 1, 2, 3, 4, 5 }; foreach (int element in myArray) { Console.WriteLine(element); }

This will output:

1 2 3 4 5
  1. Array methods: The System.Array class provides various methods to work with arrays, such as Sort, Reverse, Copy, Clear, etc. For example:
csharp
int[] myArray = { 5, 4, 3, 2, 1 }; Array.Sort(myArray); // sorts the array in ascending order
  1. Jagged arrays: A jagged array is an array of arrays, where each array can have a different length. Here's an example:
csharp
int[][] jaggedArray = new int[3][]; jaggedArray[0] = new int[] { 1, 2 }; jaggedArray[1] = new int[] { 3, 4, 5 }; jaggedArray[2] = new int[] { 6 }; // accessing elements int element = jaggedArray[1][2]; // gets the third element of the second array (which is 5)

I hope this helps! Let me know if you have any more questions

No comments:

Post a Comment

Draw Circle in C#

 Here's an example program in C# that uses the `System.Drawing` namespace to draw a circle on a Windows Form: // Mohit Kumar Tyagi using...