Fundamental Boxing Question / C #

Is it possible to change the value stored inside bar after adding it?

I tried boxing the string foo , but it does not work.

 string foo = "aaaaaaa"; var bar = new System.Web.UI.HtmlControls.HtmlGenericControl("div") { InnerHtml =foo }; foo = "zzzzzz"; plcBody.Controls.Add(bar);//want this to contain 'zzzzzz' 
+4
source share
1 answer

To do this, you need to set a value, for example:

 string foo = "aaaaaaa"; var bar = new System.Web.UI.HtmlControls.HtmlGenericControl("div") { InnerHtml = foo }; bar.InnerHtml = "zzzzzz"; plcBody.Controls.Add(bar); 

Strings themselves are immutable (at least in .NET this is not universal), you cannot change it after passing it ... you passed the value of a variable, which is a link to a string - you did not pass a link to the original variable , so changing the source variable to reference another line does nothing. When you change a variable, you change which line foo refers to, rather than editing the original line as immutable.

If it’s easier for you to think, you pass in β€œwhat foo means” is not β€œ foo itself”, therefore, as soon as this line goes into what you pass, it has nothing to do with the original variable.

+7
source

Source: https://habr.com/ru/post/1309764/


All Articles