I am writing a powershell script which use my own DLL in it:
[System.Reflection.Assembly]::LoadFile("E:\Group.School.dll")
I want to access a static method in Student class
. That static method has been overloaded.
Class Student
{
public static sting GetData(string id)
{
....
}
public static sting GetData(string fName, string lName)
{
....
}
}
From PowerShell I am going to access the first method like below:
$data = [Group.School.Student]::GetData
$data.Invoke("myId")
This gives me an exception saying
Exception calling "Invoke" with "1" argument(s): "Exception calling "GetData" with "1" argument(s): "Object reference not set to an instance of an object.""
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
A static method is the one which you can call without instantiating the class. If you want to call a static method of the superclass, you can call it directly using the class name.
A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.
Static Function Members By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.
The original code contains a few typos (e.g. Class
, sting
) and a mistake - the class has to be public
.
Here is the corrected code which works without errors:
# the corrected code added inline (might be in a DLL, as well):
Add-Type @'
public class Student
{
public static string GetData(string id)
{
return "data1";
}
public static string GetData(string fName, string lName)
{
return "data2";
}
}
'@
# call the static method:
[Student]::GetData('myId')
Try:
[Group.School.Student]::GetData('myId')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With