1

I have a menu that I dynamically create like this:

ContextMenu MenuNote = new ContextMenu();
    
MenuNote.MenuItems.AddRange(new MenuItem[]
{
      new MenuItem() { Name = "open", Text = "Ouvrir"},
      new MenuItem() { Name = "mute", Text = "Sourdine"},
      new MenuItem() { Name = "exit", Text = "Quitter" }
});

I don't create a reference because I wouldn't need these objects afterwards except for their respective events.

I then tried to do something like this, but I get an error that I cannot identify :

new MenuItem() { Name = "open", Text = "Ouvrir"}.Click += new EventHandler(MenuOpen_Click)

I get this error, and my research on "adding an event to an unreferenced object" didn't help me

Cannot implicitly convert type 'void' to 'System.Windows.Forms.MenuItem'

Do I really need to create references for each Items am I just wrong in the syntax ?

Thanks

3
  • 1
    To be exact: your MenuItem objects are referenced, because they are part of the MenuNote.MenuItems collection; you just don't have any variable assigned. You might still access them using MenuNote.MenuItems[index]. Commented Jan 30, 2021 at 15:46
  • @KlausGütter Yes you're right, sorry if I don't use the right words. Indeed, I manage to access it thanks to the index, but I would have liked to know if it was possible to do it in one line, as in my example. thank you for your reply Commented Jan 30, 2021 at 15:50
  • See e.g. here: stackoverflow.com/questions/3993601/…. This was considered for C#6 but AFAIK never made it into the language. It might however be possible to write an Extension method for MenuItem that allows s similar syntax. Commented Jan 30, 2021 at 16:00

1 Answer 1

2

Assigning event handlers in object initializers was considered for C#6 but AFAIK never made it into the language, see Assigning events in object initializer.

You could write an extension method allowing you to add an event handler with a fluent syntax:

static class MenuItemExtensions
{
    public static MenuItem OnClick(this MenuItem menuItem, EventHandler handler)
    {
        menuItem.Click += handler;
        return menuItem;
    }
}

Use:

MenuNote.MenuItems.AddRange(new MenuItem[]
{
      new MenuItem() { Name = "open", Text = "Ouvrir"}.OnClick(MenuOpen_Click),
      new MenuItem() { Name = "mute", Text = "Sourdine"}.OnClick(MenuMute_Click),
      new MenuItem() { Name = "exit", Text = "Quitter" }.OnClick(MenuExit_Click)
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. I have marked the topic resolved, but if the only solution is to do another method, I will keep the indexes with MenuItems[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.