I am trying to call my custom C# dll in powershell and facing the issue for the need to pass parameters while creating the object. Is there someway I can call method of the class without facing this issue?
In actual code, the parameterized constructor is having another class as parameter and so on, which is creating a issue for me, since I need to call the classes with parameters again and again.
Sample code:
C# Code:
namespace TestApplication{
public class Program
{
readonly string test="";
public Program(string Test)
{
this.test = Test;
Console.WriteLine("I am called as well");
}
public static void Main(string[] args)
{
Program pro = new Program("GFG");
Console.WriteLine("program = " + pro.test);
Console.WriteLine("I am called");
Console.Read();
}
public int Sum(int a, int b)
{
return a + b;
}
}
}
Your code wouldn’t work as posted. You only have a constructor that takes a string, so your attempt to create an instance would error there is no matching constructor. I’ll assume you just missed it while typing up your example.
Don’t limit yourself. You can simply extend that class however you’d like. Here we have our own custom class that handles the instantiation (only once in a session, which you can see via the output.
$csharp = @'
using System;
namespace TestApplication {
public class Program
{
public Program()
{
Console.WriteLine("Default constructor");
}
readonly string test="";
public Program(string Test)
{
this.test = Test;
Console.WriteLine("I am called as well");
}
public static void Main(string[] args)
{
Program pro = new Program("GFG");
Console.WriteLine("program = " + pro.test);
Console.WriteLine("I am called");
Console.Read();
}
public int Sum(int a, int b)
{
return a + b;
}
}
}
'@
Add-Type -Language CSharp $csharp
class MyBetterApplication {
static [int] Sum ($a,$b) {
if(-not $script:Application){
$script:Application = New-Object -TypeName TestApplication.Program
}
return $script:Application.Sum($a,$b)
}
}
[MyBetterApplication]::Sum(2,3)
[MyBetterApplication]::Sum(8,5)