Reputation: 188
I would like to call a non-static method from a static method located in a different class. I know the instance of the class from which I would like to call the method from but I am not able to access it.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
Helper _Helper = new Helper(this);
}
public void DoSmth(string input)
{
Console.WriteLine(input);
}
}
public class Helper
{
MainForm _mainform = null;
public Helper(MainForm mainform)
{
_mainform = mainform;
_mainform.DoSmth("test"); //ok
}
public static void Test ()
{
_mainform.DoSmth("test"); //generates error
}
}
Upvotes: 1
Views: 2595
Reputation: 20764
You can not access non static context inside static context.
You can make _mainform
static
static MainForm _mainform = null;
or pass the instance you want to test to Test
method
public static void Test(MainForm mainForm)
{
mainForm.DoSmth("test");
}
or make Test
non static
public void Test()
{
_mainform.DoSmth("test");
}
All aside you should revise your design. Think about these questions. If I have a static method why it should access an instance member? If a method should access instance members then why should it be static?
Upvotes: 5