Reputation: 4942
I'm looking at the source of a web application and I can see loads of use cases like my sample code below. I can't find any info online about when declaring a local variable in C# (of a 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'd imagine it always creates a reference unless it's 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;
Am I right in thinking that the following line isn't needed.
// Save back to the session
this.Session["VAR_1"] = (object) myVarA;
As the local variable myVarA
is just a reference to the property in the session so if you update the local var then you'll also be updating the session object?
Secondly, could this pose a problem when each web page is served in a new thread that these multiple threads will be accessing the same session object and doing manipulations at the same time?
Upvotes: 3
Views: 99
Reputation: 3787
struct
) are 'by
value', clasess (declared as class
) are 'by reference'. So it
depends on what CustomItemType
is.lock
block.Upvotes: 2