Is it possible to make a switch statement which checks on a Message.Contains statement?
So instead of this:
if (ex.Message.Contains("hnummer"))
{
MessageBox.Show("Deze laptop staat al in de lijst");
}
if (ex.Message.Contains("serienummmer"))
{
MessageBox.Show("Dit serienummer staat al in de lijst");
}
if (ex.Message.Contains("olcnummer"))
{
MessageBox.Show("Dit OLC nummer staat al in de lijst");
}
A switch statement?
Another way would be to use a Dictionary
//of course, the "staat al in de lijst" could be a constant, as we like DRY
var messageDictionary = new Dictionary<string, string>() {
{"hnummer", "Deze laptop staat al in de lijst"},
{"serienummmer", "Dit serienummer staat al in de lijst"}
}
then something like that (if you want multiple messagebox for each "successfull" contains test, as your code suggests).
foreach (var kvp in messageDictionary) {
if (ex.Message.Contains(kvp.Key))
Messagebox.Show(kvp.Value);
//break; if you wanna stop after first match.
}
or if you want to test all "contains" but get only one aggregated message
var res = string.Empty;
foreach (var kvp in messageDictionary) {
if (ex.Message.Contains(kvp.Key))
res +=kvp.Value;
}
MessageBox.Show(res);
or a "don't do that" oneliner way
MessageBox.Show(string.Join("\n", messageDictionary.Select(m => ex.Message.Contains(m.Key) ? m.Value : string.Empty)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With