Unsafe code to change length (by mutating!) Of String object?

Since .NET does not use the C null style to end the string, how can I save the selected string, but change its length using unsafe code?

As I understand it, using a 20-byte header for each line, presumably this is where the length of the string is stored, is there anyway the ability to directly change this length? Therefore, .NET will save the string in memory, but when I call .Length , it will return .Length me.

if possible, it would also be interesting to hear all the crazy possible side effects of this

UPDATE

I am trying to accomplish this without using reflection.

+6
source share
2 answers

From String UNDOCUMENTED

 public static unsafe void SetLength(string s, int length) { fixed(char *p = s) { int *pi = (int *)p; if (length<0 || length > pi[-2]) throw( new ArgumentOutOfRangeException("length") ); pi[-1] = length; p[length] = '\0'; } } 
+4
source

You can use Reflection to set the m_StringLength field.

0
source

Source: https://habr.com/ru/post/901772/


All Articles