How would you solve it?
This Call to C#
Add-Type -Language CSharpVersion3 -TypeDefinition @" using System; using System.Collections.Generic; using System.Linq; public class TestClass { public void Test(IEnumerable<int> id) { id.ToList().ForEach(i=> Console.WriteLine("{0}\r", i)); } } "@ (New-Object TestClass).Test((1,2,3))
Results in this Error
Cannot convert argument "id", with value: "System.Object[]", for "Test" to type
"System.Collections.Generic.IEnumerable`1[System.Int32]": "Cannot
convert the "System.Object[]" value of type "System.Object[]" to type
"System.Collections.Generic.IEnumerable`1[System.Int32]"."
At C:\testClass1.ps1:12 char:1
+ (New-Object TestClass).Test((1,2,3))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
One Solution
In PowerShell, I can code around it by explicitly typing the array. I don’t like it, too much typing.
(New-Object TestClass).Test([int[]](1,2,3))
Thoughts
Since I have access to the C# source, I’d prefer to use int[] id and not use IEnumerable for the parameter in the Test method. This way, when others work with my code from PowerShell the principal of least surprise is at work. How much do I trade doing it this way? Is it only style points?
How would you solve it?





{ 3 comments… read them below or add one }
Hi,
The method you use there where you provide the type is the bread and butter method with which I would do that.
There is a liberal use of Get-Member to determine the type available and their useage, but on the whole, I’ll use powershell to examine the assembly and it’s useage – and usually add type accelleators.
Should there be the situation exist where there are lots of extension methods – and their use significantly decreases the friction, then I’ll also make sure that I include the extension methods too ( using Bart De Smet’s technique here http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx
Thanks for the comment James and the link. It’s funny, I linked to that De Smet post when it first came out.
I agree with you. I guess another question is. If I’m designing the C# library to be consumed, should I prefer int[] id over IEnumerable? That way, in this case, a PowerShell developer won’t hit the skids when calling the method and need to do the extra work of figuring things out.
I am a huge fan of PowerShell being able to work around this. Especially when I don’t have the source code.
As a developer of libraries and a PowerShell user, I can make choices to ensure these play well together. I’m considering the trade-offs.
Some developers I talk too are adamant about the use and style of IEnumerable.
Just curious.
Thanks
Doug
About Bart De Smet’s post you can see this code here :
http://www.developpez.net/forums/d958369/applications/projets/projets-heberges/dvp-net/module-powershell-methodes-dextension/