Reputation: 170479
I need a .NET 3.5 class more or less equivalent to C++ std::vector
:
earlier I used ArrayList
and it is quite right except it stores object
and I have to cast the retrieved objects to the right type and I can add just anything there and this makes compile-time type checking harder.
Is there anything like ArrayList
but parameterized by contained type?
Upvotes: 0
Views: 490
Reputation: 1499770
Sounds like you're after List<T>
. For example, to create a list of integers:
List<int> integers = new List<int>();
integers.Add(5); // No boxing required
int firstValue = integers[0]; // Random access
// Iteration
foreach (int value in integers)
{
Console.WriteLine(value);
}
Note that you may wish to expose such lists via IEnumerable<T>
, ICollection<T>
or IList<T>
rather than via the concrete type.
You don't need .NET 3.5 for these - they were introduced in .NET 2 (which is when generics were introduced as a feature). In .NET 3.5, however, there's LINQ which makes working with sequences of any kind easier:
IEnumerable<int> evenIntegers = integers.Where(x => x % 2 == 0);
(and much more).
Upvotes: 5
Reputation: 47038
Substitute T
with your type.
Example
// Create an empty List<int>
List<int> numbers = new List<int>();
numbers.Add(4);
// Use the c# collection initializer to add some default values;
List<int> numbersWithInitializer = new List<int> { 1, 4, 3, 4 };
Upvotes: 4