38

I have third party DLL(written in c#)

That has a class called DBConnection and static method called Connect When I call that method from my C# console application like below it will work fine.

DataPackage.Db.DBConnection.Connect()

Next I tried to do the same thing using powershell.

[DataPackage.Db.DBConnection]::Connect()

But that gives me error

Exception calling "Connect" with "0" argument(s): "Object reference not set to an instance of an object."

What is the reason for this and how to fix this??

2
  • 1
    It may be helpful to tell us what the third party library is and point us to any documentation on the class/method. Commented Aug 2, 2013 at 11:05
  • the error above points to the fact that connect() needs to be called from an instance of the class, so a simple x= new-object [DataPackage.Db.DBConnection] or similar followed by x.connect() will resolve this. :) Commented Aug 19, 2016 at 8:11

3 Answers 3

45

I hate to drop an answer without a reference beyond personal experience, but I have never found an explanation for this behavior, so sorry this is not more informative.

When calling a parameterless method leave off the parens. So for your example do:

[DataPackage.Db.DBConnection]::Connect

instead of ...Connect()

Sign up to request clarification or add additional context in comments.

Comments

2

That's not a problem with PowerShell per se because your method call is indeed correct. Apparently the method itself tries to dereference null somewhere. Maybe other methods have to be called first, or maybe a static property set somewhere.

2 Comments

Is there any way to fix this or determine what is the actual cause.?
Looking in the code, I guess, i.e. disassembling it. I'm still trying ti think of a way why this won't be triggered in C#, apparently
0

I had the same issue with calling the following method in C# with powershell.

$base64 = [System.Convert]::ToBase64String($bytes)

In Powershell ISE it worked fine... yet through C# I got unclear errors:

System.Management.Automation.ExtendedTypeSystemException: The following exception occurred while retrieving member "ToBase64String": "GenericArguments[0], 'System.ReadOnlySpan`1[System.Byte]', on 'System.Func`3[T1,T2,TResult]' violates the constraint of type 'T1'."

I ended up changing how to call the method. The following works:

$base64 = [System.Convert].GetMethod('ToBase64String', [byte[]]).Invoke($null, @(,$bytes))

I'm not quite sure if this is a syntax issue or that different frameworks are being used when calling Powershell through C#

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.