0
votes

Does the .NET runtime maintain object references when serializing to SQL Session State/InProc Session State; during serialization/deserialization? In the following example, I'd expect the references to point to the same object. Can someone explain why this isn't the case.

E.g.:

var list = new List<Foo> { new Foo { Name = "foo" }, new Foo { Name = "bar" } };

var bar = list.Single(x => x.Name == "bar" );

Session["list"] = list;
Session["bar"] = bar;

var listDeserialized = (List<Foo>)Session["list"];
var barDeserialized = (Foo)Session["bar"];

Assert.IsTrue(Object.ReferenceEquals(listDeserialized[1], bar)); // false

/* class definition */
[Serializable]
public class Foo {
    public string Name { get; set; }
}

Note: Assume that the list and bar objects have already been serialized/persisted to SQL.

1
How could it possibly maintain the same reference? The reference is just a pointer to a piece of memory so once you deserialize it'll allocate a new piece of memory and put the object into it. - DoctorMick

1 Answers

1
votes

Yes because it uses BinaryFormatter for serialization which preserves the object tree as it was. See details here: http://msdn.microsoft.com/en-us/library/aa479041.aspx#aspnetsessionstate_topic5

Some methods on serialization, like XML and Soap, would definitely create 2 different objects after de-serializing; but Binary serialization, the one used to preserve Asp.Net Session State in SQL, does preserve the object tree and will make both references in your example point to the same physical object in memory.