switch Expression as a replacement for "if" statements #8109
Replies: 5 comments 2 replies
-
I assume you find the already existing terse syntax unappealing? var status = Input.MatterStage.AsText().Equals("Intake") ? PacketStatus.Prospective
: Input.MatterStage.AsText().Equals("Closed") ? PacketStatus.Archived
: PacketStatus.Active; |
Beta Was this translation helpful? Give feedback.
-
Rust-like block expression is also useful here:
|
Beta Was this translation helpful? Give feedback.
-
Can't you use this? var Status = Input.MatterStage.AsText() switch {
"Intake" => PacketStatus.Prospective,
"Closed" => PacketStatus.Archived,
_ => PacketStatus.Active,
}; |
Beta Was this translation helpful? Give feedback.
-
Personally, I'd use a dictionary for such matters to promote scalability while improving debugability and making the concern of my code being terse an obsolete thought: private static readonly Dictionary<string, PacketStatus> _mappings = new(capacity: 2)
{
{ "Intake", PacketStatus.Prospective },
{ "Closed", PacketStatus.Archived }
};
...
var matterStage = Input.MatterStage.AsText();
if (_mappings.TryGetValue(matterStage, out var status))
return status;
return PacketStatus.Active; |
Beta Was this translation helpful? Give feedback.
-
If you know all the values you will receive, definitely a Dictionary mapping or a readonly struct can be convenient in this context. [DebuggerDisplay("{Name,nq}")] // show nice in debugger.
public readonly struct LogLevel
{
// .NET don't allow us seal struct, so parameterless constructor must exists unfortunately.
public LogLevel()
{
}
// Only specific values are allowed
LogLevel(char shortName, string fullName)
{
ShortName = shortName;
Name = fullName;
}
public char ShortName { get; }
public string Name {get; }
public static LogLevel Information { get; } = new ('I', nameof(Information));
// ...other values...
public static LogLevel Verbose { get; } = new ('V', nameof(Verbose));
// add comparation, if ShortName == (char)0 then its invalid LogLevel value.
// or create separated field to handle all Unknown values.
// IEnumerable<LogLevel> Values to map all values.
} Something like i did in my lobby server emulation for an game. The player class must have both ID 0~4 and Flags (combined: |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
The switch expression is a really nice replacement for some
if
statements, however, sometimes it can be verbose when you do things like this:It would be nice if you could switch on
_
and then omit the_ when
in the expression:Beta Was this translation helpful? Give feedback.
All reactions