Link to home
Start Free TrialLog in
Avatar of FrancineTaylor
FrancineTaylor

asked on

Altering memory directly with C is easy; can it be done in C#?

I started thinking about how to make applications more secure, and a question popped into my head.  I've looked into working with unsafe pointers in C#, but mostly that just deals with the reading of information.

Given this piece of code:

string a = "one";
string b = a;
ChangeTheMiddleLetter(b, 'X');
MessageBox.Show(a);
ChangeTheMiddleLetter(b, 'n');
MessageBox.Show(a);


Could you code ChangeTheMiddleLetter such that the message box would show "oXe" the first time and "one" the second?

In other words, assuming that a and b both point to the same memory location, could you alter one character of what is being pointed to without altering the pointer address?  Or is that no longer possible with managed code?
Avatar of Aaron Jabamani
Aaron Jabamani
Flag of United Kingdom of Great Britain and Northern Ireland image

The same functionality can be done by c sharpstring methods . Why you want do using pointers?
Yes agreed with apeter

Unsafe string manipulation is inherently incorrect. .NET strings aren't supposed to be edited, and it's most likely that there is code in the framework that is built around the assumption that a string will never change. Anything that relies on String.GetHashCode() comes immediately to mind, but there might be behind-the-scenes optimizations or sanity checks. Presumably it's something like that can cause the CLR error.

If you're finding, after profiling, that .NET's immutable string implementation does not fit your needs, the easiest mutable alternative that would let you modify its length is a List<char>.
ASKER CERTIFIED SOLUTION
Avatar of Dennis Aries
Dennis Aries
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial