[SOLVED] Why can I not register to events passed as arguments?

This is my code:

using System.IO;
using System;

public class MyClass1{
   
   event Action _myEvent;
   
    public MyClass1(){
        var m = new MyClass2(_myEvent);
        _myEvent();
    }
   
}

public class MyClass2{
    public MyClass2(Action _event){
        _event += MyFunction;
    }
   
    void MyFunction(){
        Console.WriteLine("Hi");
    }
}

class Program
{
   
   
    static void Main()
    {
        var m = new MyClass1();
    }
}

It seems MyClass2 is not registering to the passed argument _myEvent. Invoking _myEvent causes a NullReferenceException even though MyClass2 should be subscribed. If I make _myEvent public and let MyClass2 register to it directly without using the event argument passed to it, it works fine.

Does adding the ref keyword help?

I have no real idea here, just grasping at straws.

1 Like

Yep you’re right :). I asked the guys on StackOverflow: c# - Why can I not register to events passed as arguments? - Stack Overflow

Apparently it’s because the way the compiler compiles it.