I have written a piece of optimized code that contains special cases for null
and empty strings. I am now trying to write a unit test for this code. In order to
You can use FastAllocateString method for that (it's being used internally in String
and StringBuilder
classes). Since it has internal static
modifier, you should use reflection to invoke. But it returns two different empty strings in a memory
var fastAllocate = typeof(string).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
.First(x => x.Name == "FastAllocateString");
string s1 = (string)fastAllocate.Invoke(null, new object[] { 0 });
string s2 = (string)fastAllocate.Invoke(null, new object[] { 0 });
var zeroLength = s1.Length == 0 && s2.Length == 0;
var notEqual = !ReferenceEquals(s1, s2);
Both checks returns true
here