by jordav at 2013-04-11 11:46:44
Greetings!by poshoholic at 2013-04-11 14:24:27
I’m having difficultly calling a static C# method from a custom C# assembly.
I’ve a small dll comprised of nothing more than:
// Add two numbers
using System;
namespace MyMethods
{
public class AddClass
{
public static long Add(long i, long j)
{
return (i + j);
}
}
}
I compile this into Test.dll, and then attempt to load it with:Add-Type -Path "C:\Users\jdav.IDI\AppData\Local\Temporary Projects\Test\bin\Debug\Test.dll"
This appears to take, as if I run:[appdomain]]
I see this among the results:GAC Version Location
---- ------------- --------------------
False v4.0.30319 C:\Users\jdav.IDI\AppData\Local\Temporary Projects\Test\bin\Debug\Test.dll
However, when I attempt to use the Add method like so:[AddClass]]
It errors with:Unable to find type [AddClass]: make sure that the assembly containing this type is loaded.
At line:1 char:1
+ [AddClass]::Add(1,2)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (AddClass:TypeName) , RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
I’ve tried this both from v3 and v2 environments. I figure I’m missing something very fundamental…please enlighten me! Thanks!
You need to either fully qualify the type name, like this][MyMethods.AddClass]]or you need to create a type accelerator for AddClass that maps to MyMethods.AddClass.by jordav at 2013-04-11 14:37:41
See this article for more details about creating type accelerators so that you don’t have to fully-qualify the .NET types you work with:
http://www.powershellmagazine.com/2012/ … -easy-way/
Ah, have definitely heard the phrase "type accelerator" before, but it didn’t click till this experiment that that’s what I was after.by poshoholic at 2013-04-11 14:42:28
Thanks a mil Kirk for the reply, your very informative writeup, and all of your other blog tips to date!
You’re welcome. I’m just glad I could help!