Hi,
Flinky Wisty Pomm wrote:
I didn't know that...
So
Foo myFoo = Session["someFoo"];
myFoo.BarString = "Rhubarb";
actually modifies the instance of Foo stored in session state?
If Foo is a class:
The "myFoo" variable will contain a reference to the instance. The
Session object also contains a reference to the same instance. The
instance itself is not contained in the Session state, just the
reference to it.
However, if Foo is a struct:
The "myFoo" variable will contain a copy of the instance contained in
the Session object (because struct are by value).
Or do
you just mean that
Session["myFoo"].BarString = "Rhubarb"; will only persist for reference
types?
No, for value types too, just the way they're stored is different.
Here's an example:
protected void Page_Load( object sender, EventArgs e )
{
if ( Session[ "Class" ] == null )
{
Session[ "Class" ] = new TestClass( "Hello" );
}
else
{
TestClass myClass = (TestClass) Session[ "Class" ];
myClass.myString = "World";
}
if ( Session[ "Struct" ] == null )
{
TestStruct myStruct = new TestStruct();
myStruct.myString = "Hello";
Session[ "Struct" ] = myStruct;
}
else
{
TestStruct myStruct = (TestStruct) Session[ "Struct" ];
myStruct.myString = "World";
}
// Displays "World"
lblClass.Text
= ( (TestClass) Session[ "Class" ] ).myString;
// Displays "Hello"
lblStruct.Text
= ( (TestStruct) Session[ "Struct" ] ).myString;
}
Greetings,
Laurent
--
Laurent Bugnion [MVP ASP.NET]
Software engineering:
http://www.galasoft-LB.ch
PhotoAlbum:
http://www.galasoft-LB.ch/pictures
Support children in Calcutta:
http://www.calcutta-espoir.ch