Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a non-static method from a static method in C#?

Tags:

c#

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 } 
like image 781
Yayan Avatar asked Sep 01 '09 01:09

Yayan


People also ask

Can I call non static method from static method?

A static method can call only other static methods; it cannot call a non-static method.

How do I call a non static method from a static function in C++?

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.

How do you reference a non static method from a static context?

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.

Can we use non static method in static class?

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.


1 Answers

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();     } } 
like image 81
tvanfosson Avatar answered Oct 06 '22 00:10

tvanfosson