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";
}
var str = (!string.IsNullOrEmpty(s2) && s2.Equals("abc")) ? "abcuser" : "xyzuser"for readability. In this case you don't add additional level of condition branching that makes expression harder to understand.s2 == "abc"is sufficient to know if it should be "abcuser".. The==operator forstrings will handle either side (or both) beingnullwithout having to test separately, and the case ofs2being empty is not worth testing because if it's empty, it can't equal "abc" anyway.