search

Arrays in C#

Sep 03, 2024 pm 03:11 PM
c#c# tutorial

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

1. Declaration of an Array

Code:

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

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;
}
}

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();
}
}

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();
}
}
}

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 
<p>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.</p>
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534749654038.png?x-oss-process=image/resize,p_40" class="lazy" alt="Arrays in C#" ></p>
<h4 id="Example">Example #3</h4>
<p>We can also use foreach to access the elements of the array</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">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);
}
}
}
}

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]

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

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></c>

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]);
}
}
}

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][];

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 };

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 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534750079716.png?x-oss-process=image/resize,p_40" class="lazy" alt="Arrays in C#" ></p>
<p><strong>Example #2</strong></p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">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 
<p><strong>Output</strong>:</p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534750158140.png?x-oss-process=image/resize,p_40" class="lazy" alt="Arrays in C#" ></p>
<h3 id="Method-of-Array-in-C">Method of Array in C#</h3>
<p>The following points are as follows:</p>
<ol>
<li>
<strong>Clear(Array, Int32, Int32)</strong>: This method is used to set the element range to default based on the type of element.</li>
<li>
<strong>Clone(): </strong>This method is used to create a copy of the element.</li>
<li>
<strong>Copy(Array, Array, Int32):</strong> This method is used to copy the elements of one array to another array.</li>
<li>
<strong>Equals(Object):</strong> This method basically checks if the mentioned object is equal to the current object.</li>
<li>
<strong>Sort(Array):</strong> This method is used to sort the array.</li>
<li>
<strong>CreateInstance(Type, Int32):</strong> This method is used to create an array of a specific type, length, and size.</li>
<li>
<strong>ToString():</strong> This is used to display string representation.</li>
<li>
<strong>GetType():</strong> This method is used to return the type of object.</li>
<li>
<strong>IndexOf(Array, Object):</strong> This method is used to search the particular object and return the first occurrence index in a 1D array.</li>
<li>
<strong>Reverse(Array):</strong> This method is used to reverse the sequence of the elements.</li>
<li>
<strong>SetValue(Object, Int32):</strong> This method in the 1D array is used to set the value of an element.</li>
</ol>
<p><strong>Example</strong></p>
<pre class="brush:php;toolbar:false">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");
}
}
}

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!

Statement
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
The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment