C# | Adding the elements to the end of the ArrayList
ArrayList.AddRange(ICollection) Method is used to add the elements of an ICollection to the end of the ArrayList.
Syntax:
public virtual void AddRange (System.Collections.ICollection c);
Here, c is the ICollection whose elements should be added to the end of the ArrayList. The collection itself cannot be null, but it can contain elements that are null.
Exceptions:
- ArgumentException: If c is null
- NotSupportedException: If the ArrayList is read-only or ArrayList has a fixed size.
Below programs illustrate the use of the above-discussed method:
Example 1:
using System;
using System.Collections;
class GFG {
public static void Main()
{
ArrayList myList = new ArrayList();
myList.Add( "A" );
myList.Add( "B" );
myList.Add( "C" );
myList.Add( "D" );
myList.Add( "E" );
myList.Add( "F" );
Console.WriteLine( "Before AddRange Method" );
Console.WriteLine();
foreach (String str in myList)
{
Console.WriteLine(str);
}
Console.WriteLine( "\nAfter AddRange Method\n" );
myList.AddRange(myList);
foreach (String str in myList)
{
Console.WriteLine(str);
}
}
}
|
Output:
Before AddRange Method
A
B
C
D
E
F
After AddRange Method
A
B
C
D
E
F
A
B
C
D
E
F
Example 2:
using System;
using System.Collections;
class GFG {
public static void Main()
{
ArrayList myList = new ArrayList();
myList.Add( "Geeks" );
myList.Add( "GFG" );
myList.Add( "C#" );
myList.Add( "Tutorials" );
Console.WriteLine( "Before AddRange Method" );
Console.WriteLine();
foreach (String str in myList)
{
Console.WriteLine(str);
}
Console.WriteLine( "\nAfter AddRange Method\n" );
string [] str_add = { "Collections" ,
"Generic" ,
"List" };
myList.AddRange(str_add);
foreach (String str in myList)
{
Console.WriteLine(str);
}
}
}
|
Output:
Before AddRange Method
Geeks
GFG
C#
Tutorials
After AddRange Method
Geeks
GFG
C#
Tutorials
Collections
Generic
List
Note:
- ArrayList accepts null as a valid value and allows duplicate elements.
- The order of the elements in the ICollection is preserved in the ArrayList.
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...