private const int RESULT_LENGTH = 10;
public static unsafe string Encode1(byte[] data)
{
var result = new string('0', RESULT_LENGTH); // memory allocation
fixed (char* c = result)
{
for (int i = 0; i < RESULT_LENGTH; i++)
{
c[i] = DetermineChar(data, i);
}
}
return result;
}
public static string Encode2(byte[] data)
{
var chars = new char[RESULT_LENGTH]; // memory allocation
for (int i = 0; i < RESULT_LENGTH; i++)
{
chars[i] = DetermineChar(data, i);
}
return new string(chars); // again a memory allocation
}
private static char DetermineChar(byte[] data, int index)
{
// dummy algorithm.
return 'a';
}
Both methods encode a byte array according some specific algorithm to a string. The first creates a string and writes to the single chars using pointers. The second creates an array of chars and eventually uses that array to instantiate a string.
I know strings are immutable and that multiple string declarations can point to the same allocated memory. Also, according to this article, you should not use unsafe string modifications unless it is absolutely necessary.
My question: When is it safe to use 'unsafe string modifications' as used in the Encode1 sample code?
PS. I'm aware of newer concepts as Span and Memory, and the string.Create method. I'm just curious about this specific case.
Edit
Thank you for all your responses.
Maybe the word 'safe' in my question was more confusing than it did any good. I didn't meant it as an opposite of the unsafe
keyword but in a vernacular sense.