public string Generate()
{
RandomNumberGenerator rdng = new RNGCryptoServiceProvider();
byte[] bytes = new byte[40];
rdng.GetBytes(bytes);
string a = Convert.ToBase64String(bytes);
a.Replace("=", "r");
a.Replace("+", "t");
return a;
}
a=43TvtRvrTrt54g5gtbrTTBR45iu+zqbB03gXej== ;
after a.Replace()
again:
a=43TvtRvrTrt54g5gtbrTTBR45iu+zqbB03gXej== ;
I want to generate unique value in my C#
project.
Everything is great.
But When I want to call string.Replace()
, it doesn't work.
Values after and before this method are the same.
Why ?
String.Replace is not modifying a, but returning a new String. As this makes it chainable, a solution could look like:
The replace method returns a new string object, it does not modify the existing string. The following statement should work:
It works. It just doesn't do what you think: it doesn't edit the existing
string
: it creates a new string. Try:This is because
string
s are immutable: they do not change once created (at least, not if you might be looking - there are some exceptions like the internals ofStringBuilder
, but those are implementation details that you shouldn't see)The problem is that the method doesn't change the string you call the method on, but returns another occurrence of the string, so you should assign it to another object in order for the changes to persist because a string is a non mutable object: