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,
  1. if (!string.IsNullOrWhiteSpace(inputString))
  2. {
  3. // do someting here
  4. }
To ignore these we generally adopt a rule to check with negate condition using the (== false) command.
For example,
  1. if (string.IsNullOrWhiteSpace(inputString) == false)
  2. {
  3. // do someting here
  4. }
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:
  1. public static bool AreTrimEqual(string input1, string input2)
  2. {
  3. return string.Equals(input1?.Trim(), input2?.Trim(), StringComparison.InvariantCultureIgnoreCase);
  4. }
  5. public static string ToTitleCase(string title)
  6. {
  7. var cultureInfo = Thread.CurrentThread.CurrentCulture;
  8. var textInfo = cultureInfo.TextInfo;
  9. return textInfo.ToTitleCase(title);
  10. }
  11. //Returns an array converted into a string
  12. public static string ArrayToString(Array input, string separator)
  13. {
  14. var ret = new StringBuilder();
  15. for (var i = 0; i < input.Length; i++)
  16. {
  17. ret.Append(input.GetValue(i));
  18. if (i != input.Length - 1)
  19. ret.Append(separator);
  20. }
  21. return ret.ToString();
  22. }
  23. //Capitalizes a word or sentence
  24. //word -> Word
  25. //OR
  26. //this is a sentence -> This is a sentence
  27. public static string Capitalize(string input)
  28. {
  29. if (input.Length == 0) return string.Empty;
  30. if (input.Length == 1) return input.ToUpper();
  31. return input.Substring(0, 1).ToUpper() + input.Substring(1);
  32. }
  33. //Checks whether a word or sentence is capitalized
  34. //Word -> True
  35. //OR
  36. //This is a sentence -> True
  37. public static bool IsCapitalized(string input)
  38. {
  39. if (input.Length == 0) return false;
  40. return string.CompareOrdinal(input.Substring(0, 1), input.Substring(0, 1).ToUpper()) == 0;
  41. }
  42. //Checks whether a string is in all lower case
  43. //word -> True
  44. //Word -> False
  45. public static bool IsLowerCase(string input)
  46. {
  47. for (var i = 0; i < input.Length; i++)
  48. {
  49. if (string.CompareOrdinal(input.Substring(i, 1), input.Substring(i, 1).ToLower()) != 0)
  50. return false;
  51. }
  52. return true;
  53. }
An exhaustive list can be found here.

1 Comment

Join the conversation! Your thoughts help the community grow.

  • 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