views:

484

answers:

3

I've discovered recently that when using the Session or Application objects within an ASP.net application, that it passes the values by reference.

This works great most of the time, but now I'm in a place where I truly need a copy of the data, and not a reference to it, since I will discard any changes to it when done processing.

I'm also aware of setting variables in the root of the application, effectively creating global application variables that have a bit better performance and eliminate all the casting craziness of the Session/Application objects.

Does anybody know if the application variables pass by reference or value? I can't seem to dig up any data on the topic and would like to eliminate the code I currently have to "copy" the data from the Application object into a new variable for processing.

+2  A: 

Actually, what happens by default (assuming you have a reference type rather than a value type) is that it passes a copy of the reference.

So you have a different variable but it's pointing at the same object.

Joel Coehoorn
Oh, I didn't know that! Thanks for the clarification. Is there any way to clone the object so I can discard the changes when done?
Dillie-O
No, you'll likely need to keep your manual copy code. .Net includes an IClonable interface you can implement, but it's not very well done. There's also .MemberWiseClone() method, but that won't do a truly deep copy either.
Joel Coehoorn
+2  A: 

This is not an ASP.NET phenomenon per se... it is inherent to the CLI in all of .NET framework. You should take a look at Jon Skeet's classic article on Parameter passing.

Assuming you are dealing with reference types, if you want to clone an object rather than simply copying a reference to the object, you will need to manually clone it. Here's a good article that explains how to deep copy an object and why the MemberwiseClone method creates only a shallow copy of the object.

Cerebrus
A: 

An "Application" variable is just a regular member variable. It works just like any other variable, it's only it's scope that is larger than most.

If the value of the variable is copied or not depends on whether the variable is a value type or not.

If it's a value type, for example int, the value is always copied.

If it's a reference type, for example a List<int> you get a copy of the reference to the object. The object itself is not copied.

So, if what you need to copy is a reference type, you have to explicitly create the copy.

Guffa
Ahh, that make sense since in this particular case, I'm working with a List<Of T> and in the past I was working with DataTables.
Dillie-O