How to manufacture an empty string in .NET?

后端 未结 3 1592
[愿得一人]
[愿得一人] 2021-01-18 13:35

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

3条回答
  •  心在旅途
    2021-01-18 14:15

    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

提交回复
热议问题