I have a class like this
class Class1
{
public Class1(Action<string> Log)
{
Log("bla bla"); // to be output by project Log system
}
}
And in the main Form project I try to pass my Log function to Class1 so inside it, I can have the same log function
public partial class Form1 : Form
{
Class1 MyClass = new Class1(Log); // ERROR !
public Form1()
{
InitializeComponent();
}
public void Log(string line)
{
rtb.Text += line + "\n";
}
...
...
}
But I got this error
Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.Log(string)'
I just need to pass Log() function pointer to other class via it's constructor, like in C I would use a function pointer to pass as argument.
If I understood right, Action is just a shortcut for a "delegate" that always return void and can have some arguments. Compiler should know that Log() exists (and so, have a address) so why I cannot pass it as argument?
Then, how can I do that in C#?