Book Image

Learn C# Programming

By : Marius Bancila, Raffaele Rialdi, Ankit Sharma
5 (1)
Book Image

Learn C# Programming

5 (1)
By: Marius Bancila, Raffaele Rialdi, Ankit Sharma

Overview of this book

The C# programming language is often developers’ primary choice for creating a wide range of applications for desktop, cloud, and mobile. In nearly two decades of its existence, C# has evolved from a general-purpose, object-oriented language to a multi-paradigm language with impressive features. This book will take you through C# from the ground up in a step-by-step manner. You'll start with the building blocks of C#, which include basic data types, variables, strings, arrays, operators, control statements, and loops. Once comfortable with the basics, you'll then progress to learning object-oriented programming concepts such as classes and structures, objects, interfaces, and abstraction. Generics, functional programming, dynamic, and asynchronous programming are covered in detail. This book also takes you through regular expressions, reflection, memory management, pattern matching, exceptions, and many other advanced topics. As you advance, you'll explore the .NET Core 3 framework and learn how to use the dotnet command-line interface (CLI), consume NuGet packages, develop for Linux, and migrate apps built with .NET Framework. Finally, you'll understand how to run unit tests with the Microsoft unit testing frameworks available in Visual Studio. By the end of this book, you’ll be well-versed with the essentials of the C# language and be ready to start creating apps with it.
Table of Contents (20 chapters)

Arrays

An array is a data structure that holds multiple values (including zero or a single one) of the same data type. It is a fixed-size sequence of homogeneous elements that are stored in contiguous memory locations. Arrays in C# are zero-indexed, meaning that the position of the first element of an array is zero and the position of the last element of the array is a total number of elements minus one.

The array type is a reference type and therefore arrays are allocated on the heap. The default value for the elements of numeric arrays is zero and for arrays of reference types, the default value is null. The type of the elements of an array can be of any type, including another array type.

Arrays in C# can be one-dimensional, multi-dimensional, or jagged. Let's explore these in detail.

One-dimensional arrays

A one-dimensional array can be defined using the syntax datatype[] variable_name. Arrays can be initialized when they are declared. If an array variable is not initialized, its value is null. You can specify the number of elements of the array when you initialize it, or you can skip this and let the compiler infer it from the initialization expression. The following sample shows various ways of declaring and initializing arrays:

int[] arr1;
int[] arr2 = null;
int[] arr3 = new int[6];
int[] arr4 = new int[] { 1, 1, 2, 3, 5, 8 };
int[] arr5 = new int[6] { 1, 1, 2, 3, 5, 8 };
int[] arr6 = { 1, 1, 2, 3, 5, 8 };

In this example, arr1 and arr2 have the value null. arr3 is an array of six integer elements all set to 0 because no initialization was provided. arr4, arr5, and arr6 are arrays of six integers, all containing the same values.

Once initialized, the size of the array cannot be changed. If you need to do so, you must either create a new array object or instead use a variable-size container, such as List<T>, which we will look at in Chapter 7, Collections.

You can access the elements of the array using the indexer, or with an enumerator. The following snippets are equivalent:

for(int i = 0; i < arr6.Length; ++i)
 Console.WriteLine(arr6[i]);
foreach(int element in arr6)
 Console.WriteLine(element);

Although the effect of these two loops is the same, there is a subtle difference—using an enumerator does not make it possible to modify the elements of the array. Accessing the elements by their index using the index operator does provide write access to the elements. Using an enumerator is possible because array types derive implicitly from the base type, System.Array, which implements IEnumerable and IEnumerable<T>.

This is shown in the following example:

for (int i = 0; i < arr6.Length; ++i)
   arr6[i] *= 2;  // OK
foreach (int element in arr6)
   element *= 2;  // error

In the first loop, we access the elements of the array by their index and can modify them. However, in the second loop, an iterator is used, and this provides read-only access to the elements. Trying to modify them produces a compile-time error.

Multi-dimensional arrays

A multi-dimensional array is an array with more than one dimension. It is also called a rectangular array. This can be, for instance, a two-dimensional array (a matrix) or a three-dimensional array (a cube). The maximum number of dimensions is 32.

A two-dimensional array can be defined using the following syntax: datatype[,] variable_name;. Multi-dimensional arrays are declared and initialized in a similar fashion with single-dimensional arrays. You can specify the rank (which is the number of elements) of each dimension or you can leave it to the compiler to infer it from an initialization expression. The following snippet shows different ways of declaring and initializing two-dimensional arrays:

int[,] arr1;
arr1 = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
int[,] arr2 = null;
int[,] arr3 = new int[2,3];
int[,] arr4 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int[,] arr5 = new int[2,3] { { 1, 2, 3 }, { 4, 5, 6 } };
int[,] arr6 = { { 1, 2, 3 }, { 4, 5, 6 } };

In this example, arr1 is initially null and then assigned a reference to an array of two rows and three columns. Similarly, arr2 is also null. On the other hand, arr3, arr4, arr5, and arr6 are arrays of two rows and three columns; arr3 has all of the elements set to zero, while the others are initialized with the specified values. The arrays in this example have the following form:

1 2 3
4 5 6

You can retrieve the number of elements of each dimension using the GetLength() or GetLongLength() methods (the first returns a 32-bit integer, the second a 64-bit integer). The following example prints the content of the arr6 array to the console:

for (int i = 0; i < arr6.GetLength(0); ++i)
{
   for (int j = 0; j < arr6.GetLength(1); ++j)
   {
      Console.Write($"{arr6[i, j]} ");
   }
   Console.WriteLine();
}

Arrays with more than two dimensions are created and handled in a similar way. The following example shows how to declare and initialize a three-dimensional array of 4 x 3 x 2 elements:

int[,,] arr7 = new int[4, 3, 2]
{
    { { 11, 12}, { 13, 14}, {15, 16 } },
    { { 21, 22}, { 23, 24}, {25, 26 } },
    { { 31, 32}, { 33, 34}, {35, 36 } },
    { { 41, 42}, { 43, 44}, {45, 46 } }
};

Another form of multi-dimensional arrays is the so-called jagged array. We will learn about this next.

Jagged arrays

Jagged arrays are arrays of arrays. These consist of other arrays, and each array inside a jagged array can be of a different size. We can declare a two-dimensional jagged array, for instance, using the syntax datatype [][] variable_name;. The following snippet shows various examples of declaring and initializing jagged arrays:

int[][] arr1;
int[][] arr2 = null;
int[][] arr3 = new int[2][];
arr3[0] = new int[3];
arr3[1] = new int[] { 1, 1, 2, 3, 5, 8 };
int[][] arr4 = new int[][]
{
   new int[] { 1, 2, 3 },
   new int[] { 1, 1, 2, 3, 5, 8 }
};
int[][] arr5 =
{
   new int[] { 1, 2, 3 },
   new int[] { 1, 1, 2, 3, 5, 8 }
};
int[][,] arr6 = new int[][,]
{
    new int[,] { { 1, 2}, { 3, 4 } },
    new int[,] { {11, 12, 13}, { 14, 15, 16} }
};

In this example, arr1 and arr2 are both set to null. On the other hand, arr3 is an array of two arrays. Its first element is set to an array of three elements that are initialized with zero; its second element is set to an array of six elements initialized from the provided values.

The arr4 and arr5 arrays are equivalent, but arr5 uses the shorthand syntax for array initialization. arr6 mixes jagged arrays with multi-dimensional arrays. It is an array of two arrays, the first one being a two-dimensional array of 2x2, and the second a two-dimensional array of 2x3 elements.

The elements of a jagged array can be accessed using the arr[i][j] syntax (this example is for two-dimensional arrays). The following snippet shows how to print the content of the arr5 array shown earlier:

for(int i = 0; i < arr5.Length; ++i)
{
   for(int j = 0; j < arr5[i].Length; ++j)
   {
      Console.Write($"{arr5[i][j]} ");
   }
   Console.WriteLine();
}

Now that we have looked at the type of arrays we can use in C#, let's move to another important topic, which is conversion between various data types.