Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
Console.Clear Method in C#
Next article icon

C# | Array.Clear() Method

Last Updated : 19 Dec, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

This method is used to set a range of elements in an array to the default value of each element type.

Syntax:

public static void Clear (Array array, int index, int length);

Parameters:

array: It is an array whose elements need to be cleared.
index: It is the starting index of the range of elements to clear.
length: It is the number of elements to clear.

Exceptions:

  • ArgumentNullException: if array is null
  • IndexOutOfRangeException: if the index is less than the lower bound of the array or the length is less than zero or the sum of index and length is greater than the size of the array.

Below are the examples to illustrate the Array.Clear() Method:

Example 1:




// C# program to demonstrate Array.Clear()
// method for int type value
using System;
using System.Collections.Generic;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Creating and initializing new the String
        int[] myArr = {10, 20, 30, 40};
  
        // Display the values of the myArr.
        Console.WriteLine("Array Before Operation:");
  
        // calling the PrintIndexAndValues() method 
        PrintIndexAndValues(myArr);
        Console.WriteLine();
  
        Array.Clear(myArr, 1, 2);
  
        // Display the values of myArr
        Console.WriteLine("Array After Operation:");
  
        // calling the PrintIndexAndValues() method
        PrintIndexAndValues(myArr);
    }
  
    // Defining the method PrintIndexAndValues 
    public static void PrintIndexAndValues(int[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
            Console.WriteLine("{0}", myArr[i]);
        }
    }
}
 
 
Output:
  Array Before Operation:  10  20  30  40    Array After Operation:  10  0  0  40  

Example 2: For ArgumentNullException




// C# program to demonstrate
// Array.Clear() method
// for ArgumentNullException
using System;
using System.Collections.Generic;
  
public class GFG {
  
    public static void Main()
    {
  
        try {
  
            // Creating and initializing 
            // new the Int with null
            int[] myArr = null;
  
            // Clearing the myArr
            // using Clear() method
            Console.WriteLine("Try to clear the element from null Array:");
            Array.Clear(myArr, 1, 2);
  
            // Display the values of myArr
            Console.WriteLine("Array after operation :");
  
            // calling the PrintIndexAndValues() method 
            PrintIndexAndValues(myArr);
        }
        catch (ArgumentNullException e) {
  
            Console.WriteLine();
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (IndexOutOfRangeException e) {
  
            Console.WriteLine();
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining the method PrintIndexAndValues 
    public static void PrintIndexAndValues(int[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
            Console.WriteLine("{0}", myArr[i]);
        }
    }
}
 
 
Output:
  Try to clear the element from null Array:    Exception Thrown: System.ArgumentNullException  

Example 3: For IndexOutOfRangeException




// C# program to demonstrate
// Array.Clear() method
// for IndexOutOfRangeException
using System;
using System.Collections.Generic;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        try {
  
            // Creating and initializing new Int array
            int[] myArr = {10, 20, 30, 40};
  
            // Display the values of myArr
            Console.WriteLine("Array Before Operation:");
  
            // calling the PrintIndexAndValues() method
            PrintIndexAndValues(myArr);
            Console.WriteLine();
  
            // Clearing the myArr
            // using Clear() method
            Console.WriteLine("Taking index out of bound:");
            Array.Clear(myArr, -1, 2);
  
            // Display the values of myArr
            Console.WriteLine("Array After Operation:");
  
            // calling the PrintIndexAndValues() method 
            PrintIndexAndValues(myArr);
        }
        catch (ArgumentNullException e) {
  
            Console.Write("Exception Thrown :");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (IndexOutOfRangeException e) {
            Console.Write("Exception Thrown :");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining the method PrintIndexAndValues 
    public static void PrintIndexAndValues(int[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
            Console.WriteLine("{0}", myArr[i]);
        }
    }
}
 
 
Output:
  Array Before Operation:  10  20  30  40    Taking index out of bound:  Exception Thrown :System.IndexOutOfRangeException  

Reference:

  • https://docs.microsoft.com/en-us/dotnet/api/system.array.clear?view=netframework-4.7.2


Next Article
Console.Clear Method in C#

R

RohitPrasad3
Improve
Article Tags :
  • C#
  • CSharp-Arrays
  • CSharp-method

Similar Reads

  • Stack.Clear Method in C#
    This method(comes under System.Collections namespace) is used to remove all the objects from the Stack. This method will set the Count of Stack to zero, and references to other objects from elements of the collection are also removed. This method is an O(n) operation, where n is Count. Syntax: publi
    2 min read
  • Queue.Clear Method in C#
    This method is used to remove the objects from the Queue. This method is an O(n) operation, where n is the total count of elements. And this method comes under System.Collections namespace. Syntax: public void Clear (); Below given are some examples to understand the implementation in a better way:
    2 min read
  • Console.Clear Method in C#
    This method is used to clear the console buffer and corresponding console window of display information. Syntax: public static void Clear (); Exceptions: This method throws IOException if an I/O error occurred. Below programs show the use of Console.Clear() method: Program 1: To display the contents
    1 min read
  • C# | Remove all elements from the ArrayList
    ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Clear method is used to remove all the elements from the ArrayLis
    3 min read
  • C# | How to insert an element in an Array?
    An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C#. Let's say we have an array and we want to insert an element at a specific position in this array. Here's how to do it. First get the element to be inserte
    2 min read
  • C# Arrays
    An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
    8 min read
  • C# | Remove a range of elements from the ArrayList
    ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.RemoveRange(Int32, Int32) method is used to remove a range of ele
    3 min read
  • C# | Remove all elements from a SortedList
    SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under System.Collections namespace. SortedList.Clear method is used to remove all the elements from a SortedList ob
    2 min read
  • C# | Remove all elements from a HashSet
    A HashSet is an unordered collection of the unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashS
    2 min read
  • C# | Remove all elements from the Hashtable
    The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Clear Method is used to remove all elements from the Hashtable. Syntax: myTable.Clear() Here myTable is the name o
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences