Is it possible to replace a substring in a string without assigning a return value?
I have a string:
string test = "Hello [REPLACE] world";
<
Strings in .NET are immutable. They cannot be edited in-line.
The closest you can get to in-line editing is to create a StringBuilder
from a string. In-line fiddles with its contents and then get it to spit a string back out again.
But this will still produce a new string rather than altering the original. It is a useful technique, though, to avoid generating lots of intermediary strings when doing lots of string fiddling, e.g. in a loop.
You can't. Strings are immutable in .NET.
As mentioned by dlev, you can't do this with string
as strings are immutable in .NET - once a string has been constructed, there's nothing you can do (excluding unsafe code or reflection) to change the contents. This makes strings generally easier to work with, as you don't need to worry about defensive copying, they're naturally thread-safe etc.
Its mutable cousin, however, is StringBuilder - which has a Replace method to perform an in-object replacement. For example:
string x = "Hello [first] [second] world";
StringBuilder builder = new StringBuilder(x);
builder.Replace("[first]", "1st");
builder.Replace("[second]", "2nd");
string y = builder.ToString(); // Value of y is "Hello 1st 2nd world"
Here is the code to fetch a string from HTML content and pass it to StringBuilder and set the value from your variable. You cannot do string.replace. You have to use StringBuilder while manipulating. Here in the HTML page I added [Name] which is replaced by Name from code behind. Make sure [Name] is unique or you can give any unique name.
string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));
StringBuilder builder = new StringBuilder(contents);
builder.Replace("[Name]", Name);
StringReader sr = new StringReader(builder.ToString());
You can't, as in C# strings are immutable. Something like this would violate that.
You need to have the return type of string, because the one you're working with cannot change.
You can't. You have to assign the value, as strings are immutable.
Built-in reference types (C# reference)