C
C#3w 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);
// ...
}
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;
}
}
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!
8 Replies
Angius
Angius3w ago
Maybe use a record?
record Config(bool Log, bool Enabled)
{
public string Say() => $"Log is {Log} and it {Enabled ? "is" : "is not"} enabled";
}
record Config(bool Log, bool Enabled)
{
public string Say() => $"Log is {Log} and it {Enabled ? "is" : "is not"} enabled";
}
Foffs
FoffsOP3w ago
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!
Angius
Angius3w ago
I can't see the boilerplate you're seeing tbh Is the repetition of GeneralConfig here the boilerplate?
public GeneralConfig General = new GeneralConfig (log, true);
public GeneralConfig General = new GeneralConfig (log, true);
Because if so, we have target-type new
public GeneralConfig General = new (log, true);
public GeneralConfig General = new (log, true);
(also, this should probably be a property or should not be public)
Foffs
FoffsOP3w ago
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
Angius
Angius3w ago
No, you can't create ad-hoc types like that
Foffs
FoffsOP3w ago
I see Thank you both for taking the time to explain it!
sibber
sibber3w ago
are you looking for tuples? use records tho, cleaner and strongly typef
Foffs
FoffsOP3w ago
Yes, it will look much nicer with records. Thank you all!

Did you find this page helpful?