Adding a delegate to C# code in powershell seems to fail it, and my question is why and if there is any workarounds to get this working (other than using Func or Action)
Testcase:
$id = get-random
$tester = Add-Type -TypeDefinition @"
using System;
public static class Class$id {
public static void test()
{
Console.WriteLine("test$id");
}
private delegate void doStuff(); // comment out this line and we are ok?
}
"@ -Language CSharp -PassThru
$tester
$tester::test()
Results in
PS C:\> $tester
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False Class897305760 System.Object
False True doStuff System.MulticastDelegate
PS C:\> $tester::test()
Method invocation failed because [System.Object[]] does not contain a method named 'test'.
At line:1 char:1
+ $tester::test()
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Removing or commenting out private delegate void doStuff();
instead runs ok:
PS C:\> $tester
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False Class883741893 System.Object
PS C:\> $tester::test()
test883741893
Here we can see that doStuff is available outside the class, not sure if that is relevant in some way.
I do intend to use the delegate, but that part of the code is not needed to reproduce the issue, so left it out.
My current workaround is to use Action<> instead, but in this case it reduces self documentation which I would like to have if at all possible.