C#C
C#8mo ago
Foffs

✅ 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:
struct GeneralConfig(bool log, bool enabled) {
  public bool Log = log;
  public bool Enabled = enabled;
}

class Config(bool log) {
  public GeneralConfig General = new GeneralConfig (log, true);
// ...
}

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:
class Config(bool log) {
  public struct General = new {
    public bool Log = log;
    public bool Enabled = true;
  }
}

The above is invalid syntax, it's just to provide an idea of what I mean.

Thank you!
Was this page helpful?