How do I call a non-static method from a static method in 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
}
Solution 1:
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();
}
}
Solution 2:
Perhaps what you are looking for is the Singleton pattern?
public class Singleton
{
private Singleton() {}
public void DoWork()
{
// do something
}
// You can call this static method which calls the singleton instance method.
public static void DoSomeWork()
{
Instance.DoWork();
}
public static Singleton Instance
{
get { return instance; }
}
private static Singleton instance = new Singleton();
}
You still have to create an instance of the class but you ensure there is only one instance.