While debugging an application or doing code review, sometimes if there is a string not-null or not-empty validation check, then it's obvious that we may ignore those negate conditions (!).
For example,
- if (!string.IsNullOrWhiteSpace(inputString))
- {
- // do someting here
- }
To ignore these we generally adopt a rule to check with negate condition using the (== false) command.
For example,
- if (string.IsNullOrWhiteSpace(inputString) == false)
- {
- // do someting here
- }
It's better to use StringUtility methods with all the possible string validation checks in one place, and use them in multiple projects as-is.
Some of the frequently used utility methods:
- public static bool AreTrimEqual(string input1, string input2)
- {
- return string.Equals(input1?.Trim(), input2?.Trim(), StringComparison.InvariantCultureIgnoreCase);
- }
- public static string ToTitleCase(string title)
- {
- var cultureInfo = Thread.CurrentThread.CurrentCulture;
- var textInfo = cultureInfo.TextInfo;
- return textInfo.ToTitleCase(title);
- }
- //Returns an array converted into a string
- public static string ArrayToString(Array input, string separator)
- {
- var ret = new StringBuilder();
- for (var i = 0; i < input.Length; i++)
- {
- ret.Append(input.GetValue(i));
- if (i != input.Length - 1)
- ret.Append(separator);
- }
- return ret.ToString();
- }
- //Capitalizes a word or sentence
- //word -> Word
- //OR
- //this is a sentence -> This is a sentence
- public static string Capitalize(string input)
- {
- if (input.Length == 0) return string.Empty;
- if (input.Length == 1) return input.ToUpper();
- return input.Substring(0, 1).ToUpper() + input.Substring(1);
- }
- //Checks whether a word or sentence is capitalized
- //Word -> True
- //OR
- //This is a sentence -> True
- public static bool IsCapitalized(string input)
- {
- if (input.Length == 0) return false;
- return string.CompareOrdinal(input.Substring(0, 1), input.Substring(0, 1).ToUpper()) == 0;
- }
- //Checks whether a string is in all lower case
- //word -> True
- //Word -> False
- public static bool IsLowerCase(string input)
- {
- for (var i = 0; i < input.Length; i++)
- {
- if (string.CompareOrdinal(input.Substring(i, 1), input.Substring(i, 1).ToLower()) != 0)
- return false;
- }
- return true;
- }
An exhaustive list can be found here.
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.
sushma guptaPosted Oct 29, 2020, 1:18 PM
Hello, thank you sharing this valuable coding knowledge with us. If you are searching for high quality skin care products online at affordable prices then I would recommend you visit Nicci Skin Care. https://nicciskincare.com/products/dandruff-shampoo