I have the following code, I want to call data1()
from data2()
. Is this possible in C#? If so, how?
private void data1() { } private static void data2() { data1(); //generates error }
A static method can call only other static methods; it cannot call a non-static method.
Solution 1. 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. Create an object of the class inside the static method and then call the non-static method using such an object.
In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created. By using the reference of the new instance, these variables can be accessed.
non-static methods can access any static method and static variable also, without using the object of the class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
You'll need to create an instance of the class and invoke the method on it.
public class Foo { public void Data1() { } public static void Data2() { Foo foo = new Foo(); foo.Data1(); } }
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