Hello,
So my question comes because I have heard different definitions of the ArrayList in C# and in Powershell and so I would like to understand this concept a little better.
In Powershell an array can be declared as follows:
$Array = @()
And you can add elements to this array by using the += operator
$Array=1 $Array+=2 $Array+=3
I used to use this method a lot, but then I heard that this method was costly because under the hood what is happening is that Powershell is actually copying all the elements to a new array plus the new one and then destroying your original array and this adds overhead, It was suggested to use ArrayList instead with the .Add() function because this will simply add the new elements to my Array without doing the whole new array, copy elements and destroy old array.
$ArrayList = New-Object System.Collections.ArrayList $ArrayList.Add(1) $ArrayList.Add(2) $ArrayList.Add(3)
Up until here we’re cool.
My confusion comes when I hear that in C# the ArrayList is actually doing that exact same thing that adds the overhead.
I heard that in C# the ArrayList will create a new array, copy all the elements plus your new one, and then delete the old array.
using System; using System.Collections; class Program { static void Main() { ArrayList list = new ArrayList(); list.Add(1); list.Add(2); list.Add(2); } }
And for C# I hear that instead we should use Lists, and the lists will add elements without this overhead.
using System; using System.Collections.Generic; class Program { static void Main() { List list = new List(); list.Add(1); list.Add(2); list.Add(2); } }
So finally my question is, did I get bad info somewhere? or something? It seems like these things should be the same, but I got 2 different definitions for C# and Powershell… so anyone know what actually happens in both scenarios?
Note: The code for List is supposed to have a lessthan; int greaterthan; right after the word List in both instances but it is not getting reflected in this post, probably not compatible with the codeblocks in this forum.