how to call static
method inside non static
method in c#
?
Interviewer gave me scenario :
class class1
{
pub
You type the method name out, and then compile and run it:
class class1
{
public static void method1(){}
public void method2()
{
method1()
}
}
class1.method1();
Same as you'd call any other static method
Apparently (as Selman22 pointed out) - the classname isn't necessary.
So
method1();
would work just as well
A normal practice is to call static method with class name.
See: Static Classes and Static Class Members (C# Programming Guide)
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
So your call would be like:
class1.method1();
But it is not necessary
You can call the static method without class name like:
method1();
But you can only do that inside the class which holds that static method, you can't call static method without class name outside of that class.
if you call the method in the some class you just call it like this
public void method2()
{
method1();
}
but if it should been called from another class you have to precede it with the name of the class
public void method2()
{
class1.method1();
}