Wednesday, December 21, 2011

Copy of Session Object

Many times we try to make copy of session object, but in case when we are modifying copied object we might noticed that session object gets updated automatically, the reason is both copied object and session object are pointing to same location, even if you tried to use "new" operator while creating object.

Scenario
Let say you have Member Class as mentioned under
public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }
}


Problem:
Member objMember = new Member();
objMember.FirstName = "Sachin";
objMember.LastName = "Tendulkar";

Then try to save object in Session
Session["MemberObj"] = objMember;

This method will work good till we are just accessing object from session, but in case if we try to update object created from session it will update value of session also.

That is,
Member newMember = new Member(); //Even though object is created using "new" keyword.
newMember = (Member) Session["MemberObj"];
newMember.FirstName = "Kapil"; //This will update session FirstName also.


Solution:
To make copies of session you need to create a clone method in class.

In above class create a method clone, to support copy of session.


public class Member{


public string FirstName { get; set; }
        public string LastName { get; set; }


public Member clone()
{
   Member cloneMember = new Member();
       cloneMember.FirstName = this.FirstName;
   cloneMember.LastName = this.LastName;
}
}

Now, while accessing session object, you can call clone method to make copy of session.

Member newMember = new Member();
newMember = ((Member) Session["MemberObj"]).clone();

now if you try to modify object copied from session, will not update session object.
newMember.FirstName = "Kapil"; //Will not update session FirstName

1 comment:

simjen said...

ah! Brillant! Worked well. Thanks

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape