Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Last active October 22, 2021 18:42
Show Gist options
  • Save DamianSuess/72c77a8fdd6771ddca15bde9c464e6b3 to your computer and use it in GitHub Desktop.
Save DamianSuess/72c77a8fdd6771ddca15bde9c464e6b3 to your computer and use it in GitHub Desktop.
Switch Expressions
// Switch Expression with partial string matching
var dict = new Dictionary<int, string>();
var files = new List<string> { "cloud-records.cfg", "ex1-usergroups.cfg", "ex1-users.cfg", "doesntbelong.cfg" };
foreach (var file in files)
{
var keyName = file switch
{
string s when s.Contains("cloud") => ConfigType.CloudConnection,
string s when s.Contains("usergroups") => ConfigType.FrameSerialNumber,
string s when s.Contains("users") => ConfigType.PCSerialNumber,
_ => ConfigFileType.Unknown,
};
dict.Add(keyName, _fileService.ReadFile(file));
// dict.SafeAdd(keyName, _fileService.ReadFile(file));
}
// Calling methods from a Switch Expression
// Note, with C# 8, you must define Action and cannot use a throw-away '_'
Action x = httpResponse.StatusCode switch
{
HttpStatusCode.Accepted => () => _log.Info("Accepted"),
HttpStatusCode.Conflict => () => _log.Warn("Conflict"),
_ => () => _log.Error($"Unexpected status code received, {response.StatusCode}"),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment