Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
can we use non static method inside static method

give some example

What I have tried:

can we use non static method inside static method

give some example
Posted
Updated 27-Mar-18 2:58am

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.

Of course you may either
  • Create an object of the class inside the static method and then call the non-static method using such an object.
or
  • Pass an instance of the class as static method parameter (and then, again, use such instance for invoking the non-static method).


Due to the vagueness of your question there can be many other ways (for instance, calling a non-static method of an object of a completely unrelated class).

Providing examples is left as an exercise.
 
Share this answer
 
Short answer: No.
You can't access the class instance from a static method of a class. Just think about: A static function does not know which instances do exist when called. It may be multiple or even none.

However, you can pass a reference to a class:
C#
class MyClass {
    void NonStaticFunc()
    {
        // Do something
    }
    
    static void StaticFunc(MyClass self)
    {
        self.NonStaticFunc();
    }
}

MyClass myclass;
myclass.NonStaticFunc();
MyClass.StaticFunc(myclass);
But that makes no sense when using it with instances of the own class. Non static functions are always called with the hidden this (C# Reference) | Microsoft Docs[^] reference.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900