C# Arrays: A Getting Started Guide (2023)

Justin Boyerarticle,not even,code quality,Justin Boyer2 reviews

You have now started your C# development journey. Learning any new language or framework can be a challenging journey. However, you don't have to despair. May those who have gone before guide you and lead you on your way. Today's tour is C# arrays.

In this article we will discuss what an array is. We'll see how to use it in your code, discuss how best to use it, and what pitfalls can hurt code quality.

Wondering if you're learning C# properly?

Download the free trial version of CodeIt.RightAnd get instant, automated code reviews.

C# Arrays: Under the Hood

If you want to use arrays in C#, you need to understand what they are and how they work. So what is an array?

A simple definition is that an array is an indexed list.This means that the field contains a collection of elements in an ordered list. Each array element must be of the same type.

In other words, you can have an array of integers or an array of strings, but not an array of integers and strings.

When initializing a C# array, the .NET runtime reserves enough memory blocks to hold the elements. It then stores the elements of the array in that memory block in order.

C# Arrays: A Getting Started Guide (1)

Declare Arrays in C#

To understand how array declarations work in C#, it's important to keep in mind the role of angle brackets in the syntax. Consider the following line of code:

string with; int n; today's date and time;

In the example above, we declared three type variablesseries,whole number, itime to get to know each other, that is. Now consider another example:

string[] name; int[] number; DateTime[] date;

In the above line of code, we declare three variables again. But this time, their guy didseries[],whole number[], iappointment time[], that is. look? "DateTime" is one type, "DateTime[]" is another (we read it as "DateTime array", "Integer array", etc.).

I've seen many younger developers struggle to understand what square brackets are for. Well done,AndA bit confusing.

Remember this when declaring an arrayThe square brackets are part of the type nameyou will be fine.

Initialize a C# field

In the previous section, we described how to declare variables that can contain strings.

But we didn't initialize the variable itself, so we'll do that now. The following code declares and initializes a variable with a five-element array of integers:

int[] my array = 新 int[5];

You can also use type inference on the left side of the declaration, making the following line equivalent to the one above:

var myArray = new int[5];

C# Arrays: A Getting Started Guide (2)

The blue blocks above represent the memory available to your computer. When the above code is executed, the runtime reserves memory and places the elements in order in the reserved memory.

Angle brackets behind each element?my stringContains the index of this element. Indexing starts at zero, so an array of five elements has indices 0, 1, 2, 3, and 4. You can access a specific array element by index, as follows:

// Get the third element of the array and store it in another variable var someElement = myArray[2]

However, you haven't actually set any values ​​to the array at this point. Let's do it next.

Assigning values ​​to strings in C#

There are two ways to put a value in a C# field. You can access each element of the array and set the value or you can useCollection initializersSyntax provided by C#. Let's look at both.

// access each individual element int[] myArray = new int[5];myArray[0] = 1;myArray[1] = 4;myArray[2] = 9;myArray[3] = 16;myArray[4 ] = 25 ;// Use collection initializerint[] myArray = new int[5] {1, 4, 9, 16, 25};// Another way to use collection initializerint[] myArray = {1, 4, 9 , 16 , 25 };

Which one do you think is better? I'll give you a hint: it's all about readability. The C# compiler converts the second and third examples into the first, so they are effectively equivalent from a clean code standpoint.

Best Mode #1: Creates an array using the collection initializer. It's more readable and, frankly, easier to type.

Lock #1: Filling strings manually can lead to hard-to-find errors and performance errors due to incorrectly entered indices. Your application will throw a runtime exception if you try to access an element that doesn't exist.

Using C# fields

C# arrays have some key characteristics that make them useful and efficient. In fact, when you dig deeper into more advanced collectionskindLists, for example, you'll see are actually array wrappers.

The array's versatility and efficiency comes from two main factors. First, they are implemented at runtime. That's why they have a special syntax that other types don't have.

For example, the List class is a C# class written by Microsoft to expose some functions. You must create a new listPurposebefore you use it.

Arrays are implemented internally at runtime, using a language closer to the metal. So you can create an array by simply adding square brackets to the type, which is unique within the type.seriesare the key building blocks of language.

Another factor in their performance advantage is the way they are stored and accessed in memory.

C# arrays are stored by reserving a block of memory equal to the number needed to hold the elements.

If you store 5 integers, each occupying 4 bytes of memory, the runtime allocates 20 bytes of memory (4 x 5) to store the values. It then puts the values ​​into the array in order, one next to the other.

So if we take our previous example, we'll initialize the array with the first five squares.

int[] my array = {1, 4, 9, 16, 25};

In memory it will look like this:

C# Arrays: A Getting Started Guide (3)

The beauty of this data structure is that the values ​​are next to each other. When you want to access an array element, just start from the beginning and jump to the number of bytes needed for the next element.

The diagram below illustrates this concept. Once you know the memory location of the first element, the rest is just a matter of adding. This is why arrays are so fast at retrieving data.

C# Arrays: A Getting Started Guide (4)

However, this efficiency comes at a price.

Once an array is created, no more elements can be added to it. This is a fixed size. There is no guarantee that the memory behind the field will be available for use. Therefore, you should not use arrays for lists of things that may change with the use of the application.

Best Mode #2: use an array when you have an immutable list. A good example is an array containing the days of the week.

Lock #2: If you need to dynamically add things to a collection, then using an array won't work for you (at least not without a lot of extra code). Use a different type of collection.

The way arrays work also means that you have to be careful about the amount of space allocated to the array. Make sure you only use the space you need.

Best Mode #3: For large lists of data, create only the array size you need. Use what you seek to keep.

Lock #3😕 If you create a large field and don't use it all, that memory will not be available to you or other applications.

C# arrays: when you need to get elements

When you want to perform an operation on all the elements of an array, you have to go through all the elements in turn and process them. This is called?repetitionon a string. There are two ways to iterate over an array in C#,forLoop ifor everyonestatement.

On the surface, the two look very similar. However, there are some important differences that you should be aware of. Let's look at the code for both and discuss the differences.

int[] myArray = {1, 4, 9, 16, 25 };for (int i = 0; i < myArray.Length; i++) { Console.WriteLine(myArray[i]); } }foreach (var broj u myArray) { Console.WriteLine(number); }

this one?for?The loop function directly accesses each element of the array and performs some operations on it using square brackets. this one?for everyoneThe loop in turn assigns the value variable of each element, and the element can then be read.

There is an important difference here:for everyoneit's a cycleread only. You cannot change the value of the elements as they pass through the loop.

return,?for everyoneThe whole sequence repeats itself anyway. If you want to iterate over only part of the array, you have to use ?for?a ring.

Best Mode #4: use?for?You need a loop if you need to iterate over part of an array, or if you need to somehow change elements of the array during iteration. use?for everyoneWhen you don't want to change anything in an array and need to iterate over all elements.

Lock #4: Do you understand the difference between them?for?i?for everyonecycle. It's not just grammar. When to use it?forWhen looping, be very careful with indexing so you don't get runtime exceptions by iterating too far and accessing elements that don't exist.

Learn more about C# arrays: Multidimensional arrays

So far we've covered one-dimensional arrays. But arrays in C# can have multiple dimensions. What does this mean in practice?

One-dimensional arrays can be used to represent data expressed in such a way that each value is associated with a single index.

For example, suppose you need to store the average temperature for the last 30 days. You can create a double field with 30 items and be done with it.

You just have to be careful not to forget that arrays are indexed from zero? So to access the first value you have to use index 0 and so on.

But what if you need to store the average daily temperature for the whole year?

Of course, you could use an array of 365 (or 366) items, but that would make it difficult to retrieve results for a specific date. A better approach might be to use a multidimensional array.

An example of a multidimensional field

See the following example:

double [,] temperature = new double [12, 31];

The above line creates a multidimensional array of dimensions 12 and 31. Visually, think of it as a table (or matrix) with 12 rows and 31 columns.

In order to assign values ​​to our multidimensional array, we need to use two indices.

In the following example, we list the average temperature for January 15:

temperature[0, 14] = 15;

You can also omit the rank of the array when you declare it, and then infer the rank from the right side of the declaration:

int[,] many = { { 1, 1 }, { 2, 3 }, { 5, 8 }, { 13, 21 } };

Note that although we use two-dimensional arrays in our examples, you are not limited to this number of dimensions. You can easily work with arrays of three, four or more dimensions.

Finally, how do we loop through a multidimensional array?

We cross one dimension in the same way: usingfororfor everyone. The only difference is what you need for multidimensional arraysnnestedfor/for everyonestructure, of whichnis the dimension of the array.

C# field as IEnumerable

This is another important feature of arrays in C#: they all implementIE countableiIEbrolive interface. In other words, if you havewhole number[], then you also have aIEbrolive.

So what is the use of this?

  • You can move through the array items usingfor everyonea ring.
  • You can use the LINQ extension method (such as selection, position and aggregation) on the string.

See the example below and notice that we need to include "System.Linq":

使用 System;using System.Linq;class MainClass { public static void Main (string[] args) { int[] 数字 = { 1, 2, 3, 4, 5 }; var squares = Numbers.Select(x => x * x); var GreaterThanFour = squares.Where(x => x > 4); var sum = GreaterThanFour.Sum(); Console.WriteLine("结果:{0}", zbroj); }}

What's next?

An array is one of the basic data structures in the C# language. Nevertheless, they are fascinating when you explore why they are special and super useful in your application. Use arrays efficiently and you will be able to build anything.

Spend some time practicing arrays and using them where they make sense in everyday coding. A solid understanding of how arrays work will help you along your journey as a software engineer.

You may also be interested in further reading about other C# language concepts:

  • list
  • Wires
  • description
  • dictionary
  • interface
  • statement switch
  • operator

Learn more about how CodeIt.Right can help you automate code review and improve code quality.

about the author

C# Arrays: A Getting Started Guide (5)

Justin Boyer

Contributing author

Justin BoyerI was a software developer for eight years, developing at all levels and using multiple languages ​​and frameworks. He recently turned to security, earning CSSLP and Security+ certifications. He blogs about application security practices and principles at Green Machine Security.

related

2Comment. leave new

C# Arrays: A Getting Started Guide (6)

Diogo Kirby - The best of Diogo Kirby

April 21, 2018 at 10:51 am

Astonishing. Thank you

Loading...

answer

[...] Note: This post originally appeared on the SubMain blog. They give you tools to help you write better C# [...]

Loading...

answer

leave feedback

FAQs

How to start an array in C#? ›

Create an Array

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: string[] cars; We have now declared a variable that holds an array of strings.

How to pass an array to a method in C sharp? ›

Example 2: Declaring, initializing, and passing the array to the method in a single line of code. Result(new int[] {1, 2, 3, 4}); Code: In the below program, we are passing the 1-D array arr to the method Result. The method is static and it will print the array elements which are passed to it.

How to initialize array with default values in C#? ›

The most basic way to initialize a string array with default values is to use the new keyword and specify the size of the Array. This will create a new string array with all elements set to null by default. This creates a string array with five elements; each initialized to null.

Do C# arrays start at 1? ›

Since arrays are objects in C#, we can find their length using member length. This is different from C/C++ where we find length using sizeof operator. A C# array variable can also be declared like other variables with [] after the data type. The variables in the array are ordered and each has an index beginning from 0.

How to initialize an array? ›

If we already know the element values we want stored in the array, we can initialize the array like this:
  1. myArray = new int[]{0, 1, 2, 3}; Java allows a shorthand of this by combining declaration and initialization:
  2. int[] myArray = {0, 1, 2, 3}; ...
  3. int myArray[] = {0, 1, 2, 3}; ...
  4. int myArray[] = new int[4];
Oct 21, 2022

What is the correct syntax to create an array? ›

Creating an Array

Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

How do you pass an entire array to a method? ›

To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

How to pass a 2D array to a method in C#? ›

C# Passing Multidimensional Array to Method

For example, to pass a 2D array of integers to a method Abc, we will write - Abc(int[,] a) . Let's look at an example. Here, the Display method is taking a 2D array of integers - Display(int[,] a) . int[, , ,] a = new int[5,6,7,3];

How do you pass an array to a set? ›

Algorithm:
  1. Get the Array to be converted.
  2. Create an empty Set.
  3. Add the array into the Set by passing it as the parameter to the Sets. newHashSet() method.
  4. Return the formed Set.
Apr 19, 2023

How to initialize an array dynamically in C#? ›

To create arrays dynamically in C#, use the ArrayList collection. It represents an ordered collection of an object that can be indexed individually. It also allows dynamic memory allocation, adding, searching and sorting items in the list.

What are the different types of arrays in C#? ›

Array elements are stored contiguously in the memory. In C#, an array can be of three types: single-dimensional, multidimensional, and jagged array.

How to fill array with 0 in C#? ›

You don't need to do anything at all. Since int is a value type, all elements are initilialized to 0 as a default. The default values of numeric array elements are set to zero, and reference elements are set to null.

Should arrays start at 0 or 1? ›

In computer science, array indices usually start at 0 in modern programming languages, so computer programmers might use zeroth in situations where others might use first, and so forth.

Do C# lists start at 0 or 1? ›

A list can be accessed by an index, a for/foreach loop, and using LINQ queries. Indexes of a list start from zero.

Do 2D arrays start at 0 or 1? ›

Notice that the array indices start at 0 and end at the length - 1. On the exam assume that any 2 dimensional (2D) array is in row-major order. The outer array can be thought of as the rows and the inner arrays the columns.

How to start from end of array in C#? ›

By adding a ^ before your array index value, C# will start at the end of the array and count backward to locate an element. ^1 refers to the last element in the array.

How to initialize a string [] in C#? ›

String arrays can be created by using the following code: string[] firstString = new String[5]; Now, we declare and initialize a C# string array by adding values to it: string[] dessert = new string[] {"Cupcake","Cake","Candy"};

Do you have to initialize an array in C#? ›

The elements of an array can be initialized to known values when the array is created. Beginning with C# 12, all of the collection types can be initialized using a Collection expression. Elements that aren't initialized are set to the default value. The default value is the 0-bit pattern.

How to initialize an array with 0 in C#? ›

You can use for loop to assign them like; int[] array = new int[10]; for(int i = 0; i < array. Length; i++) array[i] = 3; If you want to give back their default values (which is 0 in this case), you can create a new array or you can use Array.

References

Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated: 28/09/2023

Views: 6065

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.