SlideShare uma empresa Scribd logo
1 de 4
Arrays in General


C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other
popular languages There are, however, a few differences that you should be aware of.

When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the
identifier is not legal syntax in C#.

  Copy Code
int[] table; // not int table[];
Another detail is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and
assign any array of int objects to it, regardless of the array's length.

  Copy Code
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

Declaring Arrays


C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The
following examples show how to declare different kinds of arrays:

Single-dimensional arrays:

  Copy Code
int[] numbers;
Multidimensional arrays:

 Copy Code
string[,] names;
Array-of-arrays (jagged):

 Copy Code
byte[][] scores;
Declaring them (as shown above) does not actually create the arrays. In C#, arrays are objects (discussed later in this tutorial) and
must be instantiated. The following examples show how to create arrays:

Single-dimensional arrays:

 Copy Code
int[] numbers = new int[5];
Multidimensional arrays:

 Copy Code
string[,] names = new string[5,4];
Array-of-arrays (jagged):

 Copy Code
byte[][] scores = new byte[5][];
for (int x = 0; x < scores.Length; x++)
{
   scores[x] = new byte[4];
}
You can also have larger arrays. For example, you can have a three-dimensional rectangular array:

 Copy Code
int[,,] buttons = new int[4,5,3];
You can even mix rectangular and jagged arrays. For example, the following code declares a single-dimensional array of three-
dimensional arrays of two-dimensional arrays of type int:

 Copy Code
int[][,,][,] numbers;

Example


The following is a complete C# program that declares and instantiates arrays as discussed above.
Copy Code
// arrays.cs
using System;
class DeclareArraysSample
{
    public static void Main()
    {
        // Single-dimensional array
        int[] numbers = new int[5];

            // Multidimensional array
            string[,] names = new string[5,4];

            // Array-of-arrays (jagged array)
            byte[][] scores = new byte[5][];

            // Create the jagged array
            for (int i = 0; i < scores.Length; i++)
            {
                scores[i] = new byte[i+3];
            }

            // Print length of each row
            for (int i = 0; i < scores.Length; i++)
            {
                Console.WriteLine(quot;Length of row {0} is {1}quot;, i, scores[i].Length);
            }
       }
}

Output


    Copy Code
Length     of   row     0   is   3
Length     of   row     1   is   4
Length     of   row     2   is   5
Length     of   row     3   is   6
Length     of   row     4   is   7

Initializing Arrays


C# provides simple and straightforward ways to initialize arrays at declaration time by enclosing the initial values in curly braces
({}). The following examples show different ways to initialize different kinds of arrays.

Note    If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default
initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you
instantiate the type.


Single-Dimensional Array


    Copy Code
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {quot;Mattquot;, quot;Joannequot;, quot;Robertquot;};
You can omit the size of the array, like this:

    Copy Code
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {quot;Mattquot;, quot;Joannequot;, quot;Robertquot;};
You can also omit the new operator if an initializer is provided, like this:

    Copy Code
int[] numbers = {1, 2, 3, 4, 5};
string[] names = {quot;Mattquot;, quot;Joannequot;, quot;Robertquot;};

Multidimensional Array
Copy Code
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {quot;Mikequot;,quot;Amyquot;}, {quot;Maryquot;,quot;Albertquot;} };
You can omit the size of the array, like this:

 Copy Code
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {quot;Mikequot;,quot;Amyquot;}, {quot;Maryquot;,quot;Albertquot;} };
You can also omit the new operator if an initializer is provided, like this:

 Copy Code
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {quot;Mikequot;, quot;Amyquot;}, {quot;Maryquot;, quot;Albertquot;} };

Jagged Array (Array-of-Arrays)


You can initialize jagged arrays like this example:

 Copy Code
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
You can also omit the size of the first array, like this:

 Copy Code
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
-or-

 Copy Code
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Notice that there is no initialization syntax for the elements of a jagged array.


Accessing Array Members


Accessing array members is straightforward and similar to how you access array members in C/C++. For example, the following
code creates an array called   numbers and then assigns a 5 to the fifth element of the array:

 Copy Code
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]:

 Copy Code
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;
The following is a declaration of a single-dimension jagged array that contains two elements. The first element is an array of two
integers, and the second is an array of three integers:

 Copy Code
int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}
};
The following statements assign 58 to the first element of the first array and 667 to the second element of the second array:

 Copy Code
numbers[0][0] = 58;
numbers[1][1] = 667;

Arrays are Objects


In C#, arrays are actually objects. System.Array is the abstract base type of all array types. You can use the properties, and
other class members, that System.Array has. An example of this would be 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 called LengthOfNumbers:

 Copy Code
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;
The System.Array class provides many other useful methods/properties, such as methods for sorting, searching, and copying
arrays.
Using foreach on Arrays


C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array.
For example, the following code creates an array called   numbers and iterates through it with the foreach statement:

 Copy Code
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
   System.Console.WriteLine(i);
}
With multidimensional arrays, you can use the same method to iterate through the elements, for example:

 Copy Code
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
   Console.Write(quot;{0} quot;, i);
}
The output of this example is:

 Copy Code
9 99 3 33 5 55

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Unitii classnotes
Unitii classnotesUnitii classnotes
Unitii classnotes
 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in C
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
Pointers
PointersPointers
Pointers
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
C Pointers
C PointersC Pointers
C Pointers
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
C# Cheat Sheet
C# Cheat SheetC# Cheat Sheet
C# Cheat Sheet
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 

Destaque (7)

Csc153 chapter 06
Csc153 chapter 06Csc153 chapter 06
Csc153 chapter 06
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
C
CC
C
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
5 arrays
5   arrays5   arrays
5 arrays
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Semelhante a C# Arrays Guide: Everything You Need to Know

Semelhante a C# Arrays Guide: Everything You Need to Know (20)

Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
Learn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysLearn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & Arrays
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arrays
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays
ArraysArrays
Arrays
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
Arrays
ArraysArrays
Arrays
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Array
ArrayArray
Array
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
 
Array.pptx
Array.pptxArray.pptx
Array.pptx
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
L10 array
L10 arrayL10 array
L10 array
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 

Mais de martha leon

Trabajo Practico Uap Arreglos
Trabajo Practico Uap ArreglosTrabajo Practico Uap Arreglos
Trabajo Practico Uap Arreglosmartha leon
 
Silabo Prog De Computadoras 2
Silabo Prog  De Computadoras 2Silabo Prog  De Computadoras 2
Silabo Prog De Computadoras 2martha leon
 
Tema2 C++ 2004 2005
Tema2 C++ 2004 2005Tema2 C++ 2004 2005
Tema2 C++ 2004 2005martha leon
 
Unidad16 Codigof1
Unidad16 Codigof1Unidad16 Codigof1
Unidad16 Codigof1martha leon
 
Ejemplos Importantisimo
Ejemplos  ImportantisimoEjemplos  Importantisimo
Ejemplos Importantisimomartha leon
 
B2 T5 Vectores Ii
B2 T5 Vectores IiB2 T5 Vectores Ii
B2 T5 Vectores Iimartha leon
 
Sem5 Interaccion Con La Computadoras Software
Sem5 Interaccion Con La Computadoras   SoftwareSem5 Interaccion Con La Computadoras   Software
Sem5 Interaccion Con La Computadoras Softwaremartha leon
 
Sem2 En El Interior De Las Computadoras Hardware I
Sem2 En El Interior De Las Computadoras   Hardware ISem2 En El Interior De Las Computadoras   Hardware I
Sem2 En El Interior De Las Computadoras Hardware Imartha leon
 
Jhtp5 20 Datastructures
Jhtp5 20 DatastructuresJhtp5 20 Datastructures
Jhtp5 20 Datastructuresmartha leon
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3martha leon
 
Sem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las ComputadorasSem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las Computadorasmartha leon
 
Sem3 En El Interior De Las Computadoras Hardware Ii
Sem3 En El Interior De Las Computadoras   Hardware IiSem3 En El Interior De Las Computadoras   Hardware Ii
Sem3 En El Interior De Las Computadoras Hardware Iimartha leon
 

Mais de martha leon (15)

Trabajo Practico Uap Arreglos
Trabajo Practico Uap ArreglosTrabajo Practico Uap Arreglos
Trabajo Practico Uap Arreglos
 
SeúDocodigo
SeúDocodigoSeúDocodigo
SeúDocodigo
 
Silabo Prog De Computadoras 2
Silabo Prog  De Computadoras 2Silabo Prog  De Computadoras 2
Silabo Prog De Computadoras 2
 
Tema2 C++ 2004 2005
Tema2 C++ 2004 2005Tema2 C++ 2004 2005
Tema2 C++ 2004 2005
 
Unidad16 Codigof1
Unidad16 Codigof1Unidad16 Codigof1
Unidad16 Codigof1
 
Ejemplos Importantisimo
Ejemplos  ImportantisimoEjemplos  Importantisimo
Ejemplos Importantisimo
 
B2 T5 Vectores Ii
B2 T5 Vectores IiB2 T5 Vectores Ii
B2 T5 Vectores Ii
 
Sem5 Interaccion Con La Computadoras Software
Sem5 Interaccion Con La Computadoras   SoftwareSem5 Interaccion Con La Computadoras   Software
Sem5 Interaccion Con La Computadoras Software
 
Sem2 En El Interior De Las Computadoras Hardware I
Sem2 En El Interior De Las Computadoras   Hardware ISem2 En El Interior De Las Computadoras   Hardware I
Sem2 En El Interior De Las Computadoras Hardware I
 
Jhtp5 20 Datastructures
Jhtp5 20 DatastructuresJhtp5 20 Datastructures
Jhtp5 20 Datastructures
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3
 
Sem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las ComputadorasSem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las Computadoras
 
Sem3 En El Interior De Las Computadoras Hardware Ii
Sem3 En El Interior De Las Computadoras   Hardware IiSem3 En El Interior De Las Computadoras   Hardware Ii
Sem3 En El Interior De Las Computadoras Hardware Ii
 
3433 Ch09 Ppt
3433 Ch09 Ppt3433 Ch09 Ppt
3433 Ch09 Ppt
 
3433 Ch10 Ppt
3433 Ch10 Ppt3433 Ch10 Ppt
3433 Ch10 Ppt
 

Último

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Último (20)

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

C# Arrays Guide: Everything You Need to Know

  • 1. Arrays in General C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences that you should be aware of. When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#. Copy Code int[] table; // not int table[]; Another detail is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length. Copy Code 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 Declaring Arrays C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The following examples show how to declare different kinds of arrays: Single-dimensional arrays: Copy Code int[] numbers; Multidimensional arrays: Copy Code string[,] names; Array-of-arrays (jagged): Copy Code byte[][] scores; Declaring them (as shown above) does not actually create the arrays. In C#, arrays are objects (discussed later in this tutorial) and must be instantiated. The following examples show how to create arrays: Single-dimensional arrays: Copy Code int[] numbers = new int[5]; Multidimensional arrays: Copy Code string[,] names = new string[5,4]; Array-of-arrays (jagged): Copy Code byte[][] scores = new byte[5][]; for (int x = 0; x < scores.Length; x++) { scores[x] = new byte[4]; } You can also have larger arrays. For example, you can have a three-dimensional rectangular array: Copy Code int[,,] buttons = new int[4,5,3]; You can even mix rectangular and jagged arrays. For example, the following code declares a single-dimensional array of three- dimensional arrays of two-dimensional arrays of type int: Copy Code int[][,,][,] numbers; Example The following is a complete C# program that declares and instantiates arrays as discussed above.
  • 2. Copy Code // arrays.cs using System; class DeclareArraysSample { public static void Main() { // Single-dimensional array int[] numbers = new int[5]; // Multidimensional array string[,] names = new string[5,4]; // Array-of-arrays (jagged array) byte[][] scores = new byte[5][]; // Create the jagged array for (int i = 0; i < scores.Length; i++) { scores[i] = new byte[i+3]; } // Print length of each row for (int i = 0; i < scores.Length; i++) { Console.WriteLine(quot;Length of row {0} is {1}quot;, i, scores[i].Length); } } } Output Copy Code Length of row 0 is 3 Length of row 1 is 4 Length of row 2 is 5 Length of row 3 is 6 Length of row 4 is 7 Initializing Arrays C# provides simple and straightforward ways to initialize arrays at declaration time by enclosing the initial values in curly braces ({}). The following examples show different ways to initialize different kinds of arrays. Note If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type. Single-Dimensional Array Copy Code int[] numbers = new int[5] {1, 2, 3, 4, 5}; string[] names = new string[3] {quot;Mattquot;, quot;Joannequot;, quot;Robertquot;}; You can omit the size of the array, like this: Copy Code int[] numbers = new int[] {1, 2, 3, 4, 5}; string[] names = new string[] {quot;Mattquot;, quot;Joannequot;, quot;Robertquot;}; You can also omit the new operator if an initializer is provided, like this: Copy Code int[] numbers = {1, 2, 3, 4, 5}; string[] names = {quot;Mattquot;, quot;Joannequot;, quot;Robertquot;}; Multidimensional Array
  • 3. Copy Code int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[2, 2] { {quot;Mikequot;,quot;Amyquot;}, {quot;Maryquot;,quot;Albertquot;} }; You can omit the size of the array, like this: Copy Code int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = new string[,] { {quot;Mikequot;,quot;Amyquot;}, {quot;Maryquot;,quot;Albertquot;} }; You can also omit the new operator if an initializer is provided, like this: Copy Code int[,] numbers = { {1, 2}, {3, 4}, {5, 6} }; string[,] siblings = { {quot;Mikequot;, quot;Amyquot;}, {quot;Maryquot;, quot;Albertquot;} }; Jagged Array (Array-of-Arrays) You can initialize jagged arrays like this example: Copy Code int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; You can also omit the size of the first array, like this: Copy Code int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; -or- Copy Code int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} }; Notice that there is no initialization syntax for the elements of a jagged array. Accessing Array Members Accessing array members is straightforward and similar to how you access array members in C/C++. For example, the following code creates an array called numbers and then assigns a 5 to the fifth element of the array: Copy Code 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]: Copy Code int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} }; numbers[1, 1] = 5; The following is a declaration of a single-dimension jagged array that contains two elements. The first element is an array of two integers, and the second is an array of three integers: Copy Code int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5} }; The following statements assign 58 to the first element of the first array and 667 to the second element of the second array: Copy Code numbers[0][0] = 58; numbers[1][1] = 667; Arrays are Objects In C#, arrays are actually objects. System.Array is the abstract base type of all array types. You can use the properties, and other class members, that System.Array has. An example of this would be 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 called LengthOfNumbers: Copy Code int[] numbers = {1, 2, 3, 4, 5}; int LengthOfNumbers = numbers.Length; The System.Array class provides many other useful methods/properties, such as methods for sorting, searching, and copying arrays.
  • 4. Using foreach on Arrays C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array called numbers and iterates through it with the foreach statement: Copy Code int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0}; foreach (int i in numbers) { System.Console.WriteLine(i); } With multidimensional arrays, you can use the same method to iterate through the elements, for example: Copy Code int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}}; foreach(int i in numbers) { Console.Write(quot;{0} quot;, i); } The output of this example is: Copy Code 9 99 3 33 5 55