简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM