C# | Insert an element into Collection<T> at specified index
Collection<T>.Insert(Int32, T) method is used to insert an element into the Collection<T> at the specified index.
Syntax:
public void Insert (int index, T item);
Parameters:
index : The zero-based index at which item should be inserted.
item : The object to insert. The value can be null for reference types.
Exception: This method will give ArgumentOutOfRangeException if index is less than zero OR index is greater than Count.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< string > myColl = new Collection< string >();
myColl.Add( "A" );
myColl.Add( "B" );
myColl.Add( "C" );
myColl.Add( "D" );
myColl.Add( "E" );
Console.WriteLine( "Count : " + myColl.Count);
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
myColl.Insert(2, "GFG" );
Console.WriteLine( "Count : " + myColl.Count);
foreach ( string str in myColl)
{
Console.WriteLine(str);
}
}
}
|
Output:
Count : 5
A
B
C
D
E
Count : 6
A
B
GFG
C
D
E
Example 2:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class GFG {
public static void Main()
{
Collection< int > myColl = new Collection< int >();
myColl.Add(2);
myColl.Add(3);
myColl.Add(4);
myColl.Add(5);
Console.WriteLine( "Count : " + myColl.Count);
foreach ( int i in myColl)
{
Console.WriteLine(i);
}
myColl.Insert(-1, 8);
Console.WriteLine( "Count : " + myColl.Count);
foreach ( int i in myColl)
{
Console.WriteLine(i);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentOutOfRangeException: Index must be within the bounds of the List.
Parameter name: index
Note:
- Collection<T> accepts null as a valid value for reference types and allows duplicate elements.
- If index is equal to Count, item is added to the end of Collection<T>.
- This method is an O(n) operation, where n is Count.
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...