Search code examples
c#memory-managementallocation

How to get string from ReadOnlyMemory<char> without allocation?


Can we get string reference from ReadonlyMemory<char> without re-allocating on heap.

ReadonlyMemory<char> someChars;//I got ReadOnlyMemory<char> from somewhere
string str = someChars.SomeMethodToGetStringWithoutAllocation();//I am looking for this

Solution

  • You should be able to reference the same memory using the TryGetString method of the MemoryMarshal class (as noted in the comments).

    However, looking at the implementation it seems like this will only work if the memory was originally obtained from a string instance otherwise this method will fail (the internal method GetObjectStartLength will return false).

    ReadOnlyMemory<char> s = "foo".AsMemory();
    var ok = System.Runtime.InteropServices.MemoryMarshal.TryGetString(s, out string s2, out int start2, out int length2);
    Console.WriteLine(ok);      // True
    Console.WriteLine(s2);      // foo
    Console.WriteLine(start2);  // 0
    Console.WriteLine(length2); // 3
    
    ReadOnlyMemory<char> s3 = "foo".ToCharArray();
    var ok2 = System.Runtime.InteropServices.MemoryMarshal.TryGetString(s3, out string s4, out int start4, out int length4);
    Console.WriteLine(ok2);     // False
    Console.WriteLine(s4);      // null
    Console.WriteLine(start4);  // 0
    Console.WriteLine(length4); // 0
    

    Note: the string reference is the original string reference. TryGetString it is like an unwrap of a ReadOnlyMemory<char>.