Variable declaration, does it create a reference to an actual object or a copy?
I am looking at the source of the web application and I can see a lot of use cases like my example code. I can't find any information online on how to declare a local variable in C # (complex type) and just want to be sure if it creates a reference or a copy of that object. Coming from a JavaScript background, I would assume that it always creates a link unless it is a primitive data type.
The code is like this
CustomItemType myVarA = (CustomItemType) this.Session["VAR_1"];
// Do some work on the properties of VAR_1
int num2 = checked (myVarA.Items.Count - 1);
int index = 0;
while (index <= num2)
{
myVarA.Items[index].StatusCode = "Posted";
checked { ++index; }
}
// Save back to the session
this.Session["VAR_1"] = (object) myVarA;
I understand correctly that the next line is unnecessary.
// Save back to the session
this.Session["VAR_1"] = (object) myVarA;
Since a local variable myVarA
is just a reference to a property in the session, so if you update the local variable then you will update the session object as well?
Second, could this be a problem when every web page is served on a new thread, that these multiple threads will access the same session object and do manipulations at the same time?
source to share
- The primitive data types and structures (declared as
struct
) are as follows: value ', clasess (declared asclass
) are "by reference". So it depends on whatCustomItemType
. - Yes, this creates a potential thread synchronization issue. In the simple case, you can place object manipulations inside a block
lock
.
source to share