Array Overview
C# Arrays are indexed from zero, that is, array indexes start from zero. Arrays work in C# similarly to how they work in most other popular languages. But there are some differences that should be noted.
When declaring an array, square brackets ([]) must follow the type, not the identifier. In C#, it is illegal syntax to put square brackets after an identifier.
int[] table; // not int table[];
Another detail is that the size of the array is not part of its type, but in C language it is part of the array type. This allows you to declare an array and assign to it an arbitrary array of int objects, regardless of the array length.
int[] numbers; // declare numbers as an int array of any size
numbers = new int[10]; // numbers is a 10-element array
numbers = new int[20]; // now it's a 20-element array
Declaration array
C# supports one-dimensional arrays, multi-dimensional arrays (rectangular arrays) and arrays of arrays (interleaved arrays). The following example shows how to declare arrays of different types:
One-dimensional array:
int[] numbers;
Multi-dimensional array:
string[,] names;
Array of arrays (interleaved):
byte[][] scores;
Declaring arrays (shown above) does not actually create them. In C#, arrays are objects (discussed later in this tutorial) and must be instantiated. The following example shows how to create an array:
One-dimensional array:
int[] numbers = new int[5];
Multi-dimensional array:
string[,] names = new string[5,4];
Array of arrays (interleaved):
byte[][] scores = new byte[5][];
for (int x = 0; x {
scores[x ] = new byte[4];
}
You can also have larger arrays. For example, you can have a three-dimensional rectangular array:
int[,,] buttons = new int[4,5,3];
You can even mix rectangular arrays and jagged arrays. For example, the following code declares a one-dimensional array of a two-dimensional array of type int and a three-dimensional array of types.
int[][,,][,] numbers;
Initializing arrays
C# provides a simple and straightforward way to initialize an array at declaration time by enclosing the initial value in curly braces ({}). The following examples show various ways to initialize arrays of different types.
Note If the array is not initialized when declared, the array members will be automatically initialized to the default initial value of the array type. Additionally, if an array is declared as a field of a type, it will be set to the default value of null when the type is instantiated.
One-dimensional array
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", " Robert"};
The size of the array can be omitted, as follows:
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};
If an initializer is provided, you can also omit the new operator, like this:
int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Matt", "Joanne", "Robert"};
Multidimensional array
int[,] numbers = new int[3, 2] { {1 , 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert" } };
The size of the array can be omitted, as follows:
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };
You can also omit new if an initializer is provided Operator, as shown below:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Mike", "Amy "}, {"Mary", "Albert"} };
Jagged array (array of arrays)
You can initialize a jagged array as shown in the following example:
int[][] numbers = new int [2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
The size of the first array can be omitted, as shown below :
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
- or -
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Please note that for interleaved arrays The elements have no initialization syntax.
Accessing array members
Accessing array members can be done directly, similar to accessing array members in C/C++. For example, the following code creates an array named numbers and then assigns 5 to the fifth element of the array:
int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;
The following code declares a multidimensional array and assigns 5 to the member located at [1, 1]:
int[,] numbers = { { 1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;
The following declares a one-dimensional jagged array, which contains two elements. The first element is an array of two integers, and the second element is an array of three integers:
int[][] numbers = new int[][] { new int[] {1, 2}, new int [] {3, 4, 5}
};
The following statement assigns 58 to the first element of the first array and 667 to the second element of the second array:
numbers[ 0][0] = 58;
numbers[1][1] = 667;
Arrays are objects
In C#, arrays are actually objects. System.Array is the abstract base type for all array types. You can use the properties that System.Array has as well as other class members. An example of this usage is using the Length property to get the length of an array. The following code assigns the length of the numbers array (which is 5) to a variable named LengthOfNumbers:
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;
The System.Array class provides many useful additional methods/properties such as methods for sorting, searching, and copying arrays.
Use foreach on arrays
C# also provides the foreach statement. This statement provides a simple, clear way to iterate through the elements of an array. For example, the following code creates an array named numbers and iterates through the array using a foreach statement:
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
System.Console.WriteLine(i);
}
Due to multi-dimensional arrays, you can use the same method to iterate through elements, for example:
int[,] numbers = numbers new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
Console.Write("{0} ", i) ;
}
The output of this example is:
9 99 3 33 5 55
However, thanks to multidimensional arrays, using nested for loops will give you better control over the array elements.
For more articles related to C# array learning, please pay attention to the PHP Chinese website!

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function