Search code examples
c#eventsdelegatesnullreferenceexceptionlinqpad

LINQPad throws NullReferenceException on valid code


I'm reading about C# events and delegates, and I'd like to copy and paste the following code into LINQPad and run it:

class Test
{
    public event EventHandler MyEvent
    {
        add
        {
            Console.WriteLine ("add operation");
        }

        remove
        {
            Console.WriteLine ("remove operation");
        }
    }

    static void Main()
    {
        Test t = new Test();

        t.MyEvent += new EventHandler (t.DoNothing);
        t.MyEvent -= null;
    }

    void DoNothing (object sender, EventArgs e)
    {
    }
}

I am importing the System namespace in Query Properties.

I can't figure out why LINQPad throws a NullReferenceException:

Message Object reference not set to an instance of an object.
Data    Data
InnerException  (null)
TargetSite  TargetSite
StackTrace     at LINQPad.ExecutionModel.ClrQueryRunner.Run()
   at LINQPad.ExecutionModel.Server.RunQuery(QueryRunner runner)
HelpLink    null
Source  LINQPad
HResult -2147467261

The same code compiles just fine if I create a project in Visual Studio, which is what I'd like to avoid.


Solution

  • You need to move your main method out of the class like this:

    void Main()
    {
        Test t = new Test();
    
        t.MyEvent += new EventHandler (t.DoNothing);
        t.MyEvent -= null;
    }
    
    class Test
    {
        public event EventHandler MyEvent
        {
            add
            {
                Console.WriteLine ("add operation");
            }
    
            remove
            {
                Console.WriteLine ("remove operation");
            }
        }
    
        public void DoNothing (object sender, EventArgs e)
        {
        }
    }
    

    This is a limitation of LinqPad.

    Cheers