1

I'm working with a powershell script to try and convert it to a C# program but I have come across a problem I am struggling with. The script uses $NameExample = @(), which I believe is just an empty array in C# - Something like decimal[] NameExample = new decimal[] {}.

Here is more of the code to help but I am mainly trying to figure out how to declare $NameExample = @() as a C# array variable, anything will help! Thanks

$counter = 0
$UnitAvgerage = 20

$NameExample=@()
$NameExample2=@()

while ($counter -lt $NameExample.Count) 
{
    $NameExample2 += $NameExample[$counter..($counter+$UnitAvg -1)] | measure-object -average
    $counter += $NameExample2
}
  • Instead of converting your code line by line it would be better to first just understand what you want to achieve. Chances are this is easy to rewrite in C# – Zun Aug 11 '22 at 15:10
  • 2
    That Powershell arrays are being appended by new items in the loop. On C# proper you'll want `List` instead – Martheen Aug 11 '22 at 15:11
  • https://www.w3schools.com/cs/cs_arrays.php – Swedo Aug 11 '22 at 15:13
  • 1
    That is poor PowerShell code to begin with, because arrays are actually of fixed size and `+=` has to reallocate on every loop iteration. As previous commenter wrote, don't use raw arrays in C# and use one of the collection types that are optimized for frequent append operations, like `System.Collections.Generic.List`. – zett42 Aug 11 '22 at 15:15
  • if your concern is the type of the array, using `dynamic` object may be the solution. you may declare the array as: `var NameExample = new List();` – Behnam Aug 11 '22 at 15:18

1 Answers1

2

Arrays are fixed-size data structures, so they cannot be built up iteratively.

PowerShell makes it seem like that is possible with +=, but what it does behind the scenes is to create a new array every time, comprising the original elements plus the new one(s).

This is quite inefficient and to be avoided, even in PowerShell code (as convenient as it is) - see this answer.

Therefore, in your C# code use an array-like (list) type that you can build up efficiently, such as System.Collections.Generic.List<T>:

using System.Collections.Generic;

// ... 

// Create a list that can grow.
// If your list must hold objects of different types, use new List<object>()
var nameExample= new List<int>();

// ... use .Add() to append a new element to the list.
nameExample.Add(42);
mklement0
  • 382,024
  • 64
  • 607
  • 775