0

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#?

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
yo3hcv
  • 1,531
  • 2
  • 17
  • 27
  • 3
    It's not complaining about the function per se, it's complaining about *when* you're trying to initialize the field. Try moving the initialization into the constructor. – Damien_The_Unbeliever Aug 09 '21 at 07:39

1 Answers1

3

You need to move the declaration into the constructor. Like this:

public partial class Form1 : Form
{
    private Class1 MyClass;

    public Form1()
    {
        InitializeComponent();
        MyClass = new Class1(Log); 
    }

    void InitializeComponent()
    {
        throw new NotImplementedException();
    }

    public void Log(string line)
    {
        
    }
}

There is an order in which parts of a class become available for initialization. Fields get declared before the constructor runs, then the constructor runs. Before the constructor runs the fields can't reference any other instance field or method on the class.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • I see.. why should I use "new Action" isn't the Log() already existing ? Can't I just pass Log ? – yo3hcv Aug 09 '21 at 07:47
  • @orfruit - Sorry, yes you can. I was playing with a few other options before this solution. I forgot to take it out. – Enigmativity Aug 09 '21 at 07:48
  • thanks for the explanation with ORDER.. now everything make sense. I just tested and works as expected. I think you should BOLD that explanation. Thanks again! – yo3hcv Aug 09 '21 at 07:54