Is it possible to have a switch in C# which checks if the value is null or empty not "" but String.Empty
? I know i can do this:
switch (text)
{
case null:
case "":
break;
}
Is there something better, because I don't want to have a large list of IF statements?
I'mm trying to replace:
if (String.IsNullOrEmpty(text))
blah;
else if (text = "hi")
blah
You can use pattern matching to test for string length (or other things). This code was tested in .NET 6 and .NET 7.
// Program.cs
Console.WriteLine(PatternMatch(null));
Console.WriteLine(PatternMatch(""));
Console.WriteLine(PatternMatch("Hello world!"));
Console.WriteLine(PatternMatch("Blah!"));
Console.WriteLine(PatternMatch("99 bottles of beer on the wall"));
string PatternMatch(string str)
{
switch (str)
{
case null: return "String is null";
case "": return "String is empty";
case var blah when str.StartsWith("Blah"): return "Blerg";
case var match when Regex.IsMatch(match, @"\d\d.*"): return "Starts with 2 digits";
case { Length: > 0 }: return str;
default: return "We should never get here";
};
}
The output should be:
String is null String is empty Hello world! Blerg Starts with 2 digits
You can do the same thing using switch expressions too.
string PatternMatch2(string str) => str switch
{
null => "String is null",
"" => "String is empty",
var blah when str.StartsWith("Blah") => "Blerg",
var match when Regex.IsMatch(match, @"\d\d.*") => "Starts with 2 digits",
{ Length: > 0 } => str,
_ => "We should never get here"
};