'C# ternary operator for optional string parameter
What is the correct/best way to handle the string as optional parameter in ternary operator:
public static void method(string s1, string s2="")
{
var str = !string.IsNullOrEmpty(s2) ? s2.Equals("abc") ? "abcuser" : "xyzuser" : "xyzuser";
Console.WriteLine(str);
}
OR
public static void method(string s1, string s2="")
{
var str = !string.IsNullOrEmpty(s2) && s2.Equals("abc") ? "abcuser" : "xyzuser";
Console.WriteLine(str);
}
Solution 1:[1]
When creating a ternary operator, it's important that you keep them as clean and simple as possible so it's easier for other developers to read. In this instance, I can't see a use for the "s1" parameter. If this is your entire method, I recommend removing it and keeping it simple. Your "s2" parameter must equal "abc" to be accepted. Hence, a null check is not required. However, if you ever need to use a check like this, I recommend using IsNullOrWhiteSpace() because it indicates whether a specified string is null, empty, or consists only of white-spaced characters. This means it will check if the string contains empty space as well. E.g. if "s2" = " ", IsNullOrEmpty() wouldn't pick that up. I will leave a code example below, with a commented out line using this string method to check for white space. However, in this instance, I suggest you only use the smaller line.
public static void method(string s1, string s2 = "") {
//var str = !string.IsNullOrWhiteSpace(s2) && s2.Equals("abc") ? "abcuser"
: "xyzuser";
var str = s2 == "abc" ? "abcuser" : "xyzuser";
Console.WriteLine(str);
}
Too make it cleaner and more optimized, if you are not using that var variable again, you could just do this.
public static void method(string s1, string s2 = "") {
Console.WriteLine(s2 == "abc" ? "abcuser" : "xyzuser");
}
Or another alternative would be to return this value as a string
public static string method(string s2 = "") {
return s2 == "abc" ? "abcuser" : "xyzuser";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Trevor Baker |
