2

In PowerShell, why can't I call the Sum() method on an int[]? For example:

[int[]]$arr = 1, 2, 3
$arr.Sum() # InvalidOperation: Method invocation failed because [System.Int32] does not contain a method named 'Sum'.

Yet, this method exists in .NET 3.5 and newer. So what's going on here?

codewario
  • 19,553
  • 20
  • 90
  • 159
  • 2
    You mean `[System.Linq.Enumerable]::Sum($arr)` ? – Santiago Squarzon Mar 18 '22 at 17:58
  • 1
    In C# it does not get invoked as a static method. So there is still something unexplained here. – codewario Mar 18 '22 at 17:59
  • 1
    Ah this is the stupid crap around LINQ and its syntactic sugar, isn't it – codewario Mar 18 '22 at 18:01
  • 1
    I believe in PS we get the methods from LINQ as static, yes. Bible here https://stackoverflow.com/questions/38360545/can-linq-be-used-in-powershell – Santiago Squarzon Mar 18 '22 at 18:02
  • 1
    It's not LINQ specifically, it's PowerShell's general lack of support for _.NET extension methods_ (which LINQ heavily relies on) that requires explicit calls via the static methods of the LINQ types. – mklement0 Mar 18 '22 at 18:39
  • @mklement0 that's why I called it "stupid crap" lol; IMO a built in type normally shouldn't be using extension methods like this, although I understand why it was implemented this way for LINQ. – codewario Mar 21 '22 at 13:33
  • 1
    Yeah, since LINQ functionality is a "cross-cutting concern", applicable to a wide range of only abstractly related types, extension methods seem like the logical choice. – mklement0 Mar 21 '22 at 13:35

0 Answers0