C
C#11mo ago
Mtax

Syntax: Using a delegate with simplified collection declaration

Working with Avalonia framework, attempting to use simplified collection declaration, however it does not seem to support setting up events that way. Is there a workaround? It would be a significant help in preventing menu/item declaration from becoming a spaghetti.
a.Menu =
[
new NativeMenuItem("Top Menu")
{
Menu =
[
new NativeMenuItem("Nested Item")
{
Click += delegate { }
}
]
}
];
a.Menu =
[
new NativeMenuItem("Top Menu")
{
Menu =
[
new NativeMenuItem("Nested Item")
{
Click += delegate { }
}
]
}
];
11 Replies
333fred
333fred11mo ago
Are you trying to add to an existing collection, or create a new collection? Also, the cognitive dissonance of using collection expressions and delegate {} syntax in the same code example hurts me
Mtax
MtaxOP11mo ago
a.Menu exists, everything else is new.
333fred
333fred11mo ago
So are you trying to add to Menu, or create a new collection?
Mtax
MtaxOP11mo ago
The Menu I need to add the delegate in is null by default, so I need to create it.
333fred
333fred11mo ago
Alright, so what's the error you're actually getting?
Mtax
MtaxOP11mo ago
If I go with Click +=, I get Invalid initializer member declarator, if I use Click = it forces me to use += on left hand side.
333fred
333fred11mo ago
I'm afraid that doesn't make much sense to me += is indeed not a thing you can do in an object initializer I don't know what the "on the left hand side" you mentioned there is
333fred
333fred11mo ago
In all likelyhood, what you need to do is this:
var nestedItem = new NativeMenuItem("Nested Item");
nestedItem.Click += delegate { };

a.Menu =
[
new NativeMenuItem("Top Menu")
{
Menu = [nestedItem]
}
];
var nestedItem = new NativeMenuItem("Nested Item");
nestedItem.Click += delegate { };

a.Menu =
[
new NativeMenuItem("Top Menu")
{
Menu = [nestedItem]
}
];
Mtax
MtaxOP11mo ago
Yeah, that is what I figured. Unfortunate, because I could have a visual hierarchy to the menu, otherwise it's mostly going to be named declarations, which get really messy to read with like 20 entries. Regardless, thanks for confirming there is no other way. I appreciate it.
333fred
333fred11mo ago
There is a proposal for supporting it: https://github.com/dotnet/csharplang/issues/5176
GitHub
[Proposal]: Compound assignment in object initializer and with ex...
Compound assignment in object initializer and with expression Proposed Prototype: Not Started Implementation: Not Started Specification: Not Started Summary Allow compound assignments like so in an...
Want results from more Discord servers?
Add your server