HomeSearch

C# Empty String Examples

Use empty strings and the string.Empty field. Test the performance of empty strings.
Empty strings. The string.Empty field is an empty string literal. It is not the same as an empty string literal constant "". There is a subtle difference.StringsIsNullOrEmpty, IsNullOrWhiteSpace
Notes, empty strings. We compare ways to create, and test, empty strings. An understanding of string literals is helpful here. There are some minor performance differences.String Literal
First example. Here we use string.Empty and "" in a C# program. The string.Empty field is initialized to "" at runtime by the .NET Framework.

And: This means string.Empty cannot be used in a switch. But we can test with string.Empty in if-statements.

If

Part 1: We assign to string.Empty. This is mostly equivalent to "". We test the variable against the constant "", which returns true.

Part 2: The program tests the Length of the Empty string. Its length is 0, so the string Empty is printed.

Console

Part 3: Here we use a switch statement on string.Empty. We cannot use string.Empty as a case, as it is not a constant.

C# program that uses string.Empty using System; class Program { static void Main() { // Part 1: initialize string to empty string field. string value = string.Empty; if (value == "") { Console.WriteLine("Empty"); } // Part 2: test against Length. if (value.Length == 0) { Console.WriteLine("Empty"); } // Part 3: switch on the string constant. // ... We cannot have string.Empty as a case. switch (value) { case "": { Console.WriteLine("Empty"); break; } } } } Output Empty Empty Empty
Benchmark, empty string. An empty string has 0 chars. These strings can be checked using a clear and efficient method. Using the fastest method can help many programs.

Version 1: We test an empty string against the empty string literal. If both strings are literals, this would be faster.

string.Intern

Version 2: This code uses string.IsNullOrEmpty, and it has slightly different logic (it handles null).

Version 3: This version uses the Length property. The Length check throws a NullReferenceException when the string is null.

Null StringsNullReferenceException

Result: For testing strings that are not constant string literals (and are not null), using Length is the fastest option.

C# program that benchmarks empty strings using System; using System.Diagnostics; class Program { static void Main() { // Get empty string. string input = "a".Replace("a", ""); int count = 0; const int m = 100000000; // Version 1: test against empty literal. Stopwatch s1 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { if (input == "") { count++; } } s1.Stop(); // Version 2: use IsNullOrEmpty. Stopwatch s2 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { if (string.IsNullOrEmpty(input)) { count++; } } s2.Stop(); // Version 3: test Length. Stopwatch s3 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { if (input.Length == 0) { count++; } } s3.Stop(); Console.WriteLine(s1.ElapsedMilliseconds); Console.WriteLine(s2.ElapsedMilliseconds); Console.WriteLine(s3.ElapsedMilliseconds); } } Output 191 ms == "" 71 ms IsNullOrEmpty 26 ms Length == 0
Benchmark, string.Empty. When you specify "" instead string.Empty, the C# compiler itself will know the value of the string data. The runtime is not a part of this decision.

Info: You can run a benchmark where string.Empty is much slower than "", by using a conditional that is removed by the C# compiler.

Version 1: This code tests the string.Empty read only field against the null literal in a tight loop.

Version 2: Here we test the empty string literal against null in a tight loop. The constant comparison can be removed at compile-time.

Result: Certain C# compiler optimizations are effective only with "", not string.Empty.

C# program that benchmarks empty strings using System; using System.Diagnostics; class Program { const int _max = 100000000; static void Main() { var s1 = Stopwatch.StartNew(); // Version 1: test string.Empty. for (int i = 0; i < _max; i++) { if (string.Empty == null) { throw new Exception(); } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: test string literal. for (int i = 0; i < _max; i++) { if ("" == null) { throw new Exception(); } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 0.57 ns string.Empty 0.28 ns ""
Implementation. Here we look inside the .NET Framework and see how the Empty field is initialized. In the String class, look at the static constructor.

And: The Empty field is assigned to the constant "". This constant is a string literal instance.

Internal implementation of string.Empty: static String() { Empty = ""; // // More initialization omitted // } Field declaration for string.Empty: public static readonly string Empty;
Switch. Because string.Empty is initialized in the static constructor for the String class, it cannot be determined when you compile your program. It is a readonly field.StaticReadonly

Important: The case statements in switches can only contain const strings. So string.Empty, a readonly field, cannot be used.

const
Notes, string switch. Internally, complex switch statements are implemented as a Dictionary, providing constant lookup times. This is sometimes a speedup.String Switch
Notes, equality operator. If you look at == in the IL, it is called op_Equality. This operator compiles to a method call (like any other). The == is just syntactic sugar.
A summary. An empty string can be checked in many ways. We choose which one depending on clarity and convention (what is used already). The string.Empty field can be used.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.