TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Int Array

These C# examples use int arrays. They initialize, assign and loop over elements.

Int arrays are common. They store many integer values.

And these values can be used in many ways. This introductory material covers int arrays, showing declarations, assignments, elements, loops and methods.

Methods

Example. This first example shows how to declare int arrays in four different ways. The first three arrays declared below are declared on single lines, while the fourth array is declared by individual assignment of the elements.

And: The message will be written to the console because the first element of each array is identical in value.

Console.WriteLine

Note: The first array element is at index 0. This is true in C# but not in VB.NET.

C# program that uses int arrays

using System;

class Program
{
    static void Main()
    {
	int[] arr1 = new int[] { 3, 4, 5 }; // Declare int array
	int[] arr2 = { 3, 4, 5 };           // Another
	var arr3 = new int[] { 3, 4, 5 };   // Another

	int[] arr4 = new int[3];            // Declare int array of zeros
	arr4[0] = 3;
	arr4[1] = 4;
	arr4[2] = 5;

	if (arr1[0] == arr2[0] &&
	    arr1[0] == arr3[0] &&
	    arr1[0] == arr4[0])
	{
	    Console.WriteLine("First elements are the same");
	}
    }
}

Output

First elements are the same

Example 2. We can use int arrays in different kinds of loops. The example shows the foreach-loop, which has simpler syntax, and the for-loop, which gives you more control and possibly greater performance.

C# program that uses int arrays in for-loop

using System;

class Program
{
    static void Main()
    {
	// Loop over array of integers.
	foreach (int id in GetEmployeeIds())
	{
	    Console.WriteLine(id);
	}
	// Loop over array of integers.
	int[] employees = GetEmployeeIds();
	for (int i = 0; i < employees.Length; i++)
	{
	    Console.WriteLine(employees[i]);
	}
    }

    /// <summary>
    /// Returns an array of integers.
    /// </summary>
    static int[] GetEmployeeIds()
    {
	int[] employees = new int[5];
	employees[0] = 1;
	employees[1] = 3;
	employees[2] = 5;
	employees[3] = 7;
	employees[4] = 8;
	return employees;
    }
}

Output

1
3
5
7
8
1
3
5
7
8

The Main method calls the GetEmployeeIds method twice. The first time it calls the method, the ints in the int array are looped over with foreach. The values are written to the screen.

Also: GetEmployeeIds shows how to return an int array from a method in the C# language.

Return

Tip: You never have to free or deallocate the memory for the int array result. It is garbage-collected.

Example 3. Next, we use int arrays in an object-oriented program design. The Employee class here stores an internal reference to an int array at the class level. This means it can modify the int array without affecting other code.

C# program that uses int array class

using System;

class Program
{
    static void Main()
    {
	// Declare new int array.
	int[] teams = new int[3];
	teams[0] = 1;
	teams[1] = 2;
	teams[2] = 3;

	// New employee that stores int array reference.
	Employee employee = new Employee(teams);

	// Loop through each int in employee's class.
	foreach (int team in employee.Teams)
	{
	    Console.WriteLine(team);
	}
    }
}

/// <summary>
/// Stores an employee and his teams.
/// </summary>
class Employee
{
    /// <summary>
    /// Int array reference at class level.
    /// </summary>
    int[] _teams;

    /// <summary>
    /// Create new employee.
    /// </summary>
    /// <param name="teams">Teams for the employee.</param>
    public Employee(int[] teams)
    {
	_teams = teams;
    }

    /// <summary>
    /// Get array of teams.
    /// </summary>
    public int[] Teams
    {
	get
	{
	    return _teams;
	}
    }
}

Output

1
2
3

In the Main method, the code initializes a new int array with three elements. This stores the team numbers that the employee belongs to. The int array here exists only in one place.

Next, the Employee constructor accepts a reference to an int array. It assigns this reference to the local reference at the class level. No element copying is done, making this code fast.

Finally: The example has a Teams property that allows external code to get the reference to the int array.

Property

Discussion. An array in the C# language is a reference type, which means it refers to another object and doesn't contain the raw data. You can copy the elements and assign them to a reference.

Arrays Tutorial: MSDN

Array elements in an int array are stored together. Therefore, using an int array is much faster than a LinkedList or ArrayList of ints when looping over the values. If you have to call Array.Resize, using List may be faster.

LinkedListArrayListArray.ResizeList

Summary. We used int arrays in a C# program. We declared int arrays in several different ways, and then tested individual elements. Int arrays can also be used as parameters and return values.

So: Int arrays, written with int[], are efficient. They are common and compatible. But they are sometimes hard to use.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf