0% found this document useful (0 votes)
55 views9 pages

Arrays As Objects (C# Programming Guide) : Example

This document discusses passing arrays as arguments to methods in C#. Arrays can be passed by reference, so methods can modify the elements. Single and multidimensional arrays can be passed. While passing the array itself by value does not allow changing the array, passing allows changing element values, which do persist after the method call. Examples demonstrate passing and modifying arrays in methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views9 pages

Arrays As Objects (C# Programming Guide) : Example

This document discusses passing arrays as arguments to methods in C#. Arrays can be passed by reference, so methods can modify the elements. Single and multidimensional arrays can be passed. While passing the array itself by value does not allow changing the array, passing allows changing element values, which do persist after the method call. Examples demonstrate passing and modifying arrays in methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Arrays as Objects (C# Programming Guide)

11/21/2017 • 1 min to read • Edit Online

In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is
the abstract base type of all array types. You can use the properties, and other class members, that 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 :

int[] numbers = { 1, 2, 3, 4, 5 };
int lengthOfNumbers = numbers.Length;

The Array class provides many other useful methods and properties for sorting, searching, and copying arrays.

Example
This example uses the Rank property to display the number of dimensions of an array.

class TestArraysClass
{
static void Main()
{
// Declare and initialize an array:
int[,] theArray = new int[5, 10];
System.Console.WriteLine("The array has {0} dimensions.", theArray.Rank);
}
}
// Output: The array has 2 dimensions.

See Also
C# Programming Guide
Arrays
Single-Dimensional Arrays
Multidimensional Arrays
Jagged Arrays
Single-Dimensional Arrays (C# Programming Guide)
11/21/2017 • 1 min to read • Edit Online

You can declare a single-dimensional array of five integers as shown in the following example:

int[] array = new int[5];

This array contains the elements from array[0] to array[4] . The new operator is used to create the array and
initialize the array elements to their default values. In this example, all the array elements are initialized to zero.
An array that stores string elements can be declared in the same way. For example:

string[] stringArray = new string[6];

Array Initialization
It is possible to initialize an array upon declaration, in which case, the rank specifier is not needed because it is
already supplied by the number of elements in the initialization list. For example:

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

A string array can be initialized in the same way. The following is a declaration of a string array where each array
element is initialized by a name of a day:

string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

When you initialize an array upon declaration, you can use the following shortcuts:

int[] array2 = { 1, 3, 5, 7, 9 };
string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

It is possible to declare an array variable without initialization, but you must use the new operator when you
assign an array to this variable. For example:

int[] array3;
array3 = new int[] { 1, 3, 5, 7, 9 }; // OK
//array3 = {1, 3, 5, 7, 9}; // Error

C# 3.0 introduces implicitly typed arrays. For more information, see Implicitly Typed Arrays.

Value Type and Reference Type Arrays


Consider the following array declaration:

SomeType[] array4 = new SomeType[10];


The result of this statement depends on whether SomeType is a value type or a reference type. If it is a value type,
the statement creates an array of 10 elements, each of which has the type SomeType . If SomeType is a reference
type, the statement creates an array of 10 elements, each of which is initialized to a null reference.
For more information about value types and reference types, see Types.

See Also
Array
C# Programming Guide
Arrays
Multidimensional Arrays
Jagged Arrays
Multidimensional Arrays (C# Programming Guide)
11/21/2017 • 2 min to read • Edit Online

Arrays can have more than one dimension. For example, the following declaration creates a two-dimensional
array of four rows and two columns.

int[,] array = new int[4, 2];

The following declaration creates an array of three dimensions, 4, 2, and 3.

int[, ,] array1 = new int[4, 2, 3];

Array Initialization
You can initialize the array upon declaration, as is shown in the following example.
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
{ "five", "six" } };

// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.


System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Getting the total count of elements or the length of a given dimension.


var allLength = array3D.Length;
var total = 1;
for (int i = 0; i < array3D.Rank; i++) {
total *= array3D.GetLength(i);
}
System.Console.WriteLine("{0} equals {1}", allLength, total);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12
// 12 equals 12

You also can initialize the array without specifying the rank.

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

If you choose to declare an array variable without initialization, you must use the new operator to assign an array
to the variable. The use of new is shown in the following example.

int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error

The following example assigns a value to a particular array element.

array5[2, 1] = 25;

Similarly, the following example gets the value of a particular array element and assigns it to variable
elementValue .

int elementValue = array5[2, 1];

The following code example initializes the array elements to default values (except for jagged arrays).

int[,] array6 = new int[10, 10];

See Also
C# Programming Guide
Arrays
Single-Dimensional Arrays
Jagged Arrays
Passing Arrays as Arguments (C# Programming
Guide)
11/21/2017 • 3 min to read • Edit Online

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can
change the value of the elements.

Passing Single-Dimensional Arrays As Arguments


You can pass an initialized single-dimensional array to a method. For example, the following statement sends an
array to a print method.

int[] theArray = { 1, 3, 5, 7, 9 };
PrintArray(theArray);

The following code shows a partial implementation of the print method.

void PrintArray(int[] arr)


{
// Method code.
}

You can initialize and pass a new array in one step, as is shown in the following example.

PrintArray(new int[] { 1, 3, 5, 7, 9 });

Example
Description
In the following example, an array of strings is initialized and passed as an argument to a PrintArray method for
strings. The method displays the elements of the array. Next, methods ChangeArray and ChangeArrayElement are
called to demonstrate that sending an array argument by value does not prevent changes to the array elements.
Code

class ArrayClass
{
static void PrintArray(string[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write(arr[i] + "{0}", i < arr.Length - 1 ? " " : "");
}
System.Console.WriteLine();
}

static void ChangeArray(string[] arr)


{
// The following attempt to reverse the array does not persist when
// the method returns, because arr is a value parameter.
arr = (arr.Reverse()).ToArray();
// The following statement displays Sat as the first element in the array.
// The following statement displays Sat as the first element in the array.
System.Console.WriteLine("arr[0] is {0} in ChangeArray.", arr[0]);
}

static void ChangeArrayElements(string[] arr)


{
// The following assignments change the value of individual array
// elements.
arr[0] = "Sat";
arr[1] = "Fri";
arr[2] = "Thu";
// The following statement again displays Sat as the first element
// in the array arr, inside the called method.
System.Console.WriteLine("arr[0] is {0} in ChangeArrayElements.", arr[0]);
}

static void Main()


{
// Declare and initialize an array.
string[] weekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

// Pass the array as an argument to PrintArray.


PrintArray(weekDays);

// ChangeArray tries to change the array by assigning something new


// to the array in the method.
ChangeArray(weekDays);

// Print the array again, to verify that it has not been changed.
System.Console.WriteLine("Array weekDays after the call to ChangeArray:");
PrintArray(weekDays);
System.Console.WriteLine();

// ChangeArrayElements assigns new values to individual array


// elements.
ChangeArrayElements(weekDays);

// The changes to individual elements persist after the method returns.


// Print the array, to verify that it has been changed.
System.Console.WriteLine("Array weekDays after the call to ChangeArrayElements:");
PrintArray(weekDays);
}
}
// Output:
// Sun Mon Tue Wed Thu Fri Sat
// arr[0] is Sat in ChangeArray.
// Array weekDays after the call to ChangeArray:
// Sun Mon Tue Wed Thu Fri Sat
//
// arr[0] is Sat in ChangeArrayElements.
// Array weekDays after the call to ChangeArrayElements:
// Sat Fri Thu Wed Thu Fri Sat

Passing Multidimensional Arrays As Arguments


You pass an initialized multidimensional array to a method in the same way that you pass a one-dimensional array.

int[,] theArray = { { 1, 2 }, { 2, 3 }, { 3, 4 } };
Print2DArray(theArray);

The following code shows a partial declaration of a print method that accepts a two-dimensional array as its
argument.
void Print2DArray(int[,] arr)
{
// Method code.
}

You can initialize and pass a new array in one step, as is shown in the following example.

Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

Example
Description
In the following example, a two-dimensional array of integers is initialized and passed to the Print2DArray method.
The method displays the elements of the array.
Code

class ArrayClass2D
{
static void Print2DArray(int[,] arr)
{
// Display the array elements.
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
System.Console.WriteLine("Element({0},{1})={2}", i, j, arr[i, j]);
}
}
}
static void Main()
{
// Pass the array as an argument.
Print2DArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });

// Keep the console window open in debug mode.


System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
Element(0,0)=1
Element(0,1)=2
Element(1,0)=3
Element(1,1)=4
Element(2,0)=5
Element(2,1)=6
Element(3,0)=7
Element(3,1)=8
*/

See Also
C# Programming Guide
Arrays
Single-Dimensional Arrays
Multidimensional Arrays
Jagged Arrays

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy