Arrays in C#

王林
Release: 2024-09-03 15:11:33
Original
470 people have browsed it

An array is a set of objects. The elements present in an array are of the same data type. It may be int, float, char, etc. The concept of Arrays in C# comes into existence to avoid the cumbersome of storing different values by making different variables.

23 56 32 54 1
0 1 2 3 4

The index of an array starts from 0, and the index of an array will be increased based on the specific size of an array. If we have an array of length 5, then the array will start from index 0 and ends at index 4. So the length of the array defines the number of elements in that array.

How does the Array work in C#?

In C#, the length of the array can be fixed or dynamic. In an array of fixed length, a fixed number of items can be stored. In a dynamic array, size increases as new items come to the array, as the memory allocation of an array is dynamic. In arrays, stack memory stores the variable of the array, whereas managed heap stores the elements. In C#, the array is derived from System. Array class. If we have an integer array, then all the elements have their respective value, and as an array in C# is a reference type, the elements will hold a reference to actual objects.

How to Create an Array in C#?

Syntax of an Array:

data_type [] name_of_array
Copy after login

1. Declaration of an Array

Code:

class Name
{
static void Main(string[]args)
{
Int32[] intarray;   //array declaration
}
}
Copy after login

Code Explanation: In the Array declaration, the first part is the datatype which defines the type of objects in an array. The second part is [], which defines the number of objects in an array, and then next is the name of the array, which is int array in this case

2. Array Initialization

Code:

class Name
{
static void Main(string[]args)
{
Int32[] Intarray;   //array declaration
Intarray = new Int32[4]; // array initialization
Intarray[0]= 23;  // assigning values to the elements
Intarray[1]=5;
Intarray[2]=88;
Intarray[3]=6;
}
}
Copy after login

Code Explanation: In array initialization, we have to specify the number of values in an array by using square brackets and assigning those values to each array element. So here, intarray[0] means that we are assigning a value in the first position, intarray[1] means assigning values in the second position, and so on.

3. Displaying values of Array

Code:

class Name
{
static void Main(string[]args)
{
Int32[] Intarray;   //array declaration
Intarray = new Int32[4]; //array initialization
Intarray[0]= 23; //assigning values to array
Intarray[1]=5;
Intarray[2]=88;
Intarray[3]=6;
Console.WriteLine(Intarray[0]);
Console.WriteLine(Intarray[1]);
Console.WriteLine(Intarray[2]);
Console.WriteLine(Intarray[3]);
Console.ReadKey();
}
}
Copy after login

Code Explanation: Console.WriteLine is a method to display each value of an array in the console.

Examples of Arrays in C#

Examples and the results in C# are Display below

Example #1

Code:

using System;
namespace ArrayDemo
{
class Name
{
static void Main(string[] args)
{
Int32[] Intarray;   // array declaration
Intarray = new Int32[4]; // array initialization
Intarray[0] = 23;   // assigning values to the array element
Intarray[1] = 5;
Intarray[2] = 88;
Intarray[3] = 6;
Console.WriteLine(Intarray[0]);
Console.WriteLine(Intarray[1]);
Console.WriteLine(Intarray[2]);
Console.WriteLine(Intarray[3]);
Console.ReadKey();
}
}
}
Copy after login

In the above code, the array is declared and initialized with four elements and Console.WriteLine displays all the values.

Output:

Arrays in C#

Example #2

Code:

using System;
namespace Demo
{
class Array
{
static void Main(string[] args)
{
int[] arr = new int[4] { 10, 20, 30, 40 };
for (int i = 0; i < arr.Length; i++)    // Traverse array elements
{
Console.WriteLine(arr[i]);
}
}
}
}
Copy after login

In the above code, the array is initialized and declared with four elements and then looping is used to access the elements of the array.

Output:

Arrays in C#

Example #3

We can also use foreach to access the elements of the array

Code:

using System;
namespace Demo
{
class Array
{
static void Main(string[] args)
{
int[] arr = new int[4] { 10, 20, 30, 40 };
foreach (int i in arr)
{
Console.WriteLine(i);
}
}
}
}
Copy after login

Output:

Arrays in C#

Types of Array in C#

In C#, we have multiple types of arrays:

  1. Single dimension array.
  2. Multi-dimension array.
  3. Jagged array.

The above examples are of Single Dimension array.

Multi-dimension Array

In rectangular arrays or multi-dimensional arrays, data is stored in tabular form.

Int[,] intArray = new int[4,3]
Copy after login

In this, we have specified the size of the array with four rows and three columns.

1. Declaration of multi-dimensional arrays

int[,] array = new int[3,3]; //declaration of 2D array
int[,,] array=new int[3,3,3]; //declaration of 3D array
Copy after login

2. Initialization of multidimensional array

int[,] array = new int[3,3]; //declaration of 2D array
array[0,1]=10; //initialization
array[1,2]=20;
array[2,0]=30;<c/ode>
Copy after login

Example of Multi-dimensional array

Code:

using System;
namespace Demo
{
class Array
{
public static void Main()
{
int[,] intArray = new int[3, 2]{
{1, 2},
{2, 4},
{4, 8}
};
Console.WriteLine(intArray[0, 0]);
Console.WriteLine(intArray[0, 1]);
Console.WriteLine(intArray[1, 0]);
Console.WriteLine(intArray[1, 1]);
Console.WriteLine(intArray[2, 0]);
Console.WriteLine(intArray[2, 1]);
}
}
}
Copy after login

Code Explanation: In the above code, rows and columns are specified with three rows and four-column and Console.WriteLine displays all the values.

Output:

Arrays in C#

Jagged Array

Elements of jagged arrays are “array” because it directly stores array.

1. Declaration of the jagged array

int[][] array = new int[3][];
Copy after login

The first bracket tells about the size and the second bracket tells about the dimensions of the array.

2. Initialization and assign values to the jagged arrays

array[0] = new int[4] { 1, 2, 3, 4 };
array[1] = new int[5] { 1, 2, 3, 4,5 };
Copy after login

The size of the elements can be different.

Below are the examples of the jagged array:

Example #1

Code:

using System;
namespace Demo
{
class Array
{
public static void Main()
{
int[][] array = new int[2][];// Declare the array
array[0] = new int[] { 1, 2, 6, 8 };// Initialize the array
array[1] = new int[] { 72, 51, 47, 23, 54, 13 };
// Traverse array elements
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
System.Console.Write(array[i][j] + " ");
}
System.Console.WriteLine();
}
}
}
}
Copy after login

Output:

Arrays in C#

Example #2

Code:

using System;
namespace Demo
{
class Array
{
public static void Main()
{
int[][] array = new int[3][]{
new int[] { 51, 22, 43, 87 },
new int[] { 2, 3, 4, 56, 94, 23 },
new int[] { 4, 5 }
};
// Traverse array elements
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array[i].Length; j++)
{
System.Console.Write(array[i][j] + " ");
}
System.Console.WriteLine();
}
}
}
}
Copy after login

Output:

Arrays in C#

Method of Array in C#

The following points are as follows:

  1. Clear(Array, Int32, Int32): This method is used to set the element range to default based on the type of element.
  2. Clone(): This method is used to create a copy of the element.
  3. Copy(Array, Array, Int32): This method is used to copy the elements of one array to another array.
  4. Equals(Object): This method basically checks if the mentioned object is equal to the current object.
  5. Sort(Array): This method is used to sort the array.
  6. CreateInstance(Type, Int32): This method is used to create an array of a specific type, length, and size.
  7. ToString(): This is used to display string representation.
  8. GetType(): This method is used to return the type of object.
  9. IndexOf(Array, Object): This method is used to search the particular object and return the first occurrence index in a 1D array.
  10. Reverse(Array): This method is used to reverse the sequence of the elements.
  11. SetValue(Object, Int32): This method in the 1D array is used to set the value of an element.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArrayMethod
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[6] { 5, 8, 9, 25, 0, 7 };
// Creating an empty array
int[] arr2 = new int[6];
Console.WriteLine("length of first array: " + arr.Length); // length of array
Array.Sort(arr);  //sorting array elements
Console.Write("Sorted array elements: ");
PrintArray(arr);
Array.Copy(arr, arr2, arr.Length);  // copy elements of one array to other
Console.Write("Second array elements: ");
PrintArray(arr2);
Console.WriteLine("Get Index:\t{0}", Array.IndexOf(arr, 9));  // index of value
Array.Reverse(arr);
Console.Write("\nFirst Array elements in reverse order: ");  // reverse the elements of array
PrintArray(arr);
Array.Clear(arr, 0, 6);  //set default value of elements
PrintArray(arr);
}
static void PrintArray(int[] arr)
{
foreach (int i in arr)
{
Console.Write("\t{0}", i);
}
Console.WriteLine("\n");
}
}
}
Copy after login

Code Explanation: The above code shows several methods of the array in which arr. Length is used to get the length which is equal to 6, Array. Sort gives the values in sorted form. Array. Copy copies the values from the first array to the second array. Array. The reverse displays the array in reverse order, whereas Clear sets the default values of the elements.

Output:

Arrays in C#

Conclusion

So it is better to declare one array variable instead of declaring too many different variables as elements in the memory are stored sequentially, which makes it faster. Also, it’s easy to traverse, manipulate and sort the data by using arrays.

The above is the detailed content of Arrays in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template