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

Xeno6x
  • 73
  • 6
  • 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]`. – Klaus Gütter Jan 30 '21 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 – Xeno6x Jan 30 '21 at 15:50
  • See e.g. here: https://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer. 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. – Klaus Gütter Jan 30 '21 at 16:00

1 Answers1

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)
});
Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
  • 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[]` – Xeno6x Jan 30 '21 at 16:13