Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a static method of a custom class

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.""

like image 481
New Developer Avatar asked Aug 01 '13 09:08

New Developer


People also ask

How do you call a static method from a class?

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.

Can we call static method of parent class?

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.

Can I call a static method inside a regular one?

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.

When can you call static functions in a class?

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 ::.


2 Answers

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')
like image 147
Roman Kuzmin Avatar answered Oct 17 '22 13:10

Roman Kuzmin


Try:

[Group.School.Student]::GetData('myId')
like image 45
Shay Levy Avatar answered Oct 17 '22 12:10

Shay Levy