void SomeFunc(string arg1, string arg2, string arg3) { string msg = ""; if (arg1 == null) msg += "ARG1 "; if (arg2 == null) msg += "ARG2 "; if (arg3 == null) msg += "ARG3 "; if (msg != "") throw new ArgumentNullException(msg); //... }
void SomeFunc(string arg1, string arg2, string arg3) { string msg = ""; if (arg1 == null) msg += "ARG1, "; if (arg2 == null) msg += "ARG2, "; if (arg3 == null) msg += "ARG3, "; if (msg.EndsWith(", ")) msg = msg.Substring(0, msg.Length - 2); if (msg != "") throw new ArgumentNullException(msg); //... }
In other words, put a separator after each word, and then “bite off” an extra separator at the end of the line. string BuildSQL(string arg1, string arg2, string arg3) { string sql = "SELECT * FROM table_1 WHERE 1=1 "; if (arg1 != null) sql += "AND ARG1 = ? "; if (arg2 != null) sql += "AND ARG1 = ? "; if (arg3 != null) sql += "AND ARG1 = ? "; return sql; }
Options, when all sorts of combinations of conditions are being recruited, I, for obvious reasons, will not consider. public static class StringEx { public static string Append(this string main, string str, string delimiter) { if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(delimiter)) return main; else if (string.IsNullOrEmpty(main) || main.Trim() == "" || str.Trim() == "" || delimiter.Trim() == "") return str; else return main + delimiter + str; } }
class ListBuilder { bool first = true; string last = ""; string content = ""; string delimiter = ", "; string lastdelimiter = " and "; public ListBuilder() { } public ListBuilder(string delimiter, string lastdelimiter) { this.delimiter = delimiter ?? ", "; this.lastdelimiter = lastdelimiter ?? " and "; } public ListBuilder(string content, string delimiter, string lastdelimiter) { this.content = content ?? ""; this.delimiter = delimiter ?? ", "; this.lastdelimiter = lastdelimiter ?? " and "; } public void Append(string str) { if (str == null || str.Trim() == "") return; // if (first) { content += str; first = false; } // else { if (last != "") content += delimiter + last; last = str; } } public override string ToString() { if (last != "") return content + lastdelimiter + last; else return content; } }
ListBuilder lb = new ListBuilder(" ", ", ", " "); foreach (string s in new string[] { "", "", "", "" }) lb.Append(s); // Console.WriteLine(lb + "!");
ListBuilder lb = new ListBuilder(", , ", ", ", " "); if (!IsAutorized()) lb.Append(" "); if (!IsAdmin()) lb.Append(" "); if (!IsBadDay()) lb.Append(" "); if (!IsAutorized() || !IsAdmin() || !IsBadDay()) Console.WriteLine(lb + ".");
Source: https://habr.com/ru/post/133805/
All Articles