TheDeveloperBlog.com

Home | Contact Us

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

C# Array.Clear Method, Zero Out Array

This C# example program uses the Array.Clear method. Clear zeros out all elements.

Array.Clear zeros out all elements.

It provides a one-line, reliable and understandable way to empty or clear your array. It works on arrays of any type—including numbers, booleans, structs and class instances.

Numbers

Example. Probably the most common types of arrays use integers or other value types such as char. In the C# language, these types of arrays are always initialized to 0, but sometimes you need to reset the same array to zeros.

Char Array

Next: We use Array.Clear to reset all elements in an int array to zero, without reallocating the array or changing its reference.

Int Array

C# program that uses Array.Clear

using System;

class Program
{
    static void Main()
    {
	int[] integerArray = new int[]
	{
	    4,
	    6,
	    8,
	    1,
	    3
	};
	//
	// Display the array
	//
	Console.WriteLine("--- Integer array before ---");
	foreach (int value in integerArray)
	{
	    Console.WriteLine(value);
	}
	//
	// Clear all elements in the array.
	//
	Array.Clear(integerArray, 0, integerArray.Length);
	//
	// Display the array
	//
	Console.WriteLine("--- Integer array after ---");
	foreach (int value in integerArray)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

--- Integer array before ---
4
6
8
1
3
--- Integer array after ---
0
0
0
0
0

The int array is declared and initialized. Next, the Array.Clear method is called. The three arguments to Array.Clear specify the array you are clearing, the starting offset to clear, and the number of elements to clear.

Then: We use the Length property of the array as the third argument. This clears all elements.

Array Length

Example 2. This example shows an array of objects, each with two properties. The Array.Clear method is used to set the first two references in the array to null. We use the Math.Min method for bounds-checking, which avoids possible exceptions.

Null

C# program that clears object array

using System;

class Program
{
    class Employee
    {
	public string Name { get; set; }
	public int Salary { get; set; }
    }

    static void Main()
    {
	Employee[] employees = new Employee[3];
	employees[0] = new Employee() { Name = "Bob", Salary = 10000 };
	employees[1] = new Employee() { Name = "Susan", Salary = 13000 };
	employees[2] = new Employee() { Name = "John", Salary = 20000 };

	//
	// Display the employee array.
	//
	Console.WriteLine("--- Employee array before ---");
	foreach (Employee employee in employees)
	{
	    Console.Write(employee.Name);
	    Console.Write(": ");
	    Console.WriteLine(employee.Salary);
	}
	//
	// Clear first two elements in employee array.
	//
	Array.Clear(employees, 0, Math.Min(2, employees.Length));

	//
	// Display the employee array.
	//
	Console.WriteLine("--- Employee array after ---");
	foreach (Employee employee in employees)
	{
	    if (employee != null)
	    {
		Console.Write(employee.Name);
		Console.Write(": ");
		Console.WriteLine(employee.Salary);
	    }
	    else
	    {
		Console.WriteLine("null");
	    }
	}
    }
}

Output

--- Employee array before ---
Bob: 10000
Susan: 13000
John: 20000
--- Employee array after ---
null
null
John: 20000

In this example, the array elements are written to the screen. Next, Array.Clear is called with three parameters. The first is the target array to clear, and the second specifies the offset to start clearing at.

The third argument uses Math.Min to clear either two elements or all elements, whichever is smaller. If you clear two elements and the array has one element, you will get an error. Math.Min prevents this exception.

Math.MinMath.Max

Discussion. You will see in the MSDN documentation that boolean arrays are cleared by having all their elements assigned to false. Also, struct arrays will be cleared the same way as other arrays of System.ValueType instances.

Note: All struct fields will be set to null or 0, depending on their type. The default value can be found with the default operator.

StructDefault

Summary. The Array.Clear method is frequently useful in programs. It provides a one-line way of resetting your entire array to its default values. It works on arrays of values and references.


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