✅ Does C# have anonymous struct initializers for class fields?
Hey, I'm new to C#. I have been refactoring the code I wrote so it looks cleaner.
I have something like this:
The code works but it has quite a bit of boilerplate, I was wondering if it's possible to declare the structure and initial values at the field definition.
Something like:
The above is invalid syntax, it's just to provide an idea of what I mean.
Thank you!
8 Replies
Maybe use a record?
Let me look it up real quick!
The
record
approach could reduce the struct declaration boilerplate but it doesn't solve the problem of code repetition.
I see, that's a shame. The anonymous type field doesn't seem to solve the problem of the amount of boilerplate.
I think I will change my struct to have a record
modifier to reduce the boilerplate and stick with it. Thank you both!I can't see the boilerplate you're seeing tbh
Is the repetition of
GeneralConfig
here the boilerplate?
Because if so, we have target-type new
(also, this should probably be a property or should not be public)It's more centered on the structure declaration, so the declaration and initialization both in-line in the field rather having to declare the structure somewhere else and reference it
But it doesn't seem possible
No, you can't create ad-hoc types like that
I see
Thank you both for taking the time to explain it!
are you looking for tuples?
use records tho, cleaner and strongly typef
Yes, it will look much nicer with records. Thank you all!