Since characters are passed by value, you would need to pass the character argument in by reference:
public static unsafe void Clear(ref char s)
{
fixed (char* n = &s)
{
*n = '\0';
}
}
In this case, unsafe code is unnecessary; the above can be rewritten as simply:
public static void Clear(ref char s)
{
s = '\0';
}
Note that since the first parameter of an extension method cannot have a ref
modifier, the above cannot be used as an extension method.
Separately, your Clear(string)
method relies on undefined behavior. While unsafe semantics do allow to mutate a string, this can cause unexpected results. Per the language specification (emphasis added):
Modifying objects of managed type through fixed pointers can results in undefined behavior. For example, because strings are immutable, it is the programmer’s responsibility to ensure that the characters referenced by a pointer to a fixed string are not modified.
To illustrate the undefined behavior, consider the following code:
string d = "E";
string f = "E";
d.Clear();
Console.WriteLine(d);
Console.WriteLine(f);
Console.WriteLine("E");
Because of string interning, the all three strings are stored in the same memory location. As a result, the code above prints three blank lines.
If the motivation for clearing the string is to clear sensitive data from memory, a supported approach is to use SecureString
. Since the GC can relocate memory as needed, there is no assurance that clearing the variable's current address will remove all references to the string from memory.