To check whether a string is empty I use
var test = string.Empty;
if (test.Length == 0) Console.WriteLine("String is empty!");
if (!(test.Any())) Console.WriteLine("String is empty!");
if (test.Count() == 0) Console.WriteLine("String is empty!");
if (String.IsNullOrWhiteSpace(test)) Console.WriteLine("String is empty!");
-
All the above statements produces the same output. What is the optimal method that I should use?
var s = Convert.ToString(test); s = test.ToString(CultureInfo.InvariantCulture); -
Again, both statements does the same thing. What is the best method to use?
I tried debugging and how to benchmark the performance of a C# statement?
First of all the 4 statemens are not giving the same output on all inputs. Try null and the first 3 will throw an exception. And try whithspaces the last one will give you a failty result. So you really have to think about what you want. The best way to go are normally the:
Only if you are doing this a few million times you should have a look on how to optimize your code further.
Here some test result, but this can differ on any .net version:
Test results for 100 million iterations:
source