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.
C#
Scenario
Let say you have Employee Class as mentioned under
publicclassEmployee
{
publicstring Emp_FName { get; set; }
publicstring Emp_LName { get; set; }
}
TypeScript
Problem:
Employee objemployee = newEmployee();
objemployee.Emp_FName = "Sachin";
objemployee.Emp_LName = "Tendulkar";
Thentry to save objectinSessionSession["EmployeeObj"] = objEmployee;
This method will work good till we are just accessing objectfrom session,
but incaseif we try to update object created from session it will update value of session also.
That is,
employee newemployee = newemployee(); //Even though object is created using "new" keyword.
newemployee = (Employee) Session["employeeObj"];
newemployee.Emp_FName = "Kapil"; //This will update session employee FirstName also.Solution:
To make copies of session you need to create a clone method inclass.
In above classcreate a method clone, to support copy of session.
publicclassEmployee{
publicstringEmp_FName { get; set; }
publicstringEmp_LName { get; set; }
publicMemberclone()
{
Employee cloneEmployee = newEmployee();
cloneEmployee.Emp_FName = this.FirstName;
cloneEmployee.Emp_LName = this.LastName;
}
}
Now, while accessing session object, you can call clone method to make copy of session.
Employee newEmployee = new Employee(); newEmployee = ((Employee) Session["EmployeeObj"]).clone();
now if you try to modify object copied from session, will not update session object. newEmployee.Emp_FName = "Kapil"; //Will not update session employee FirstName
0 comments
Comments
Join the conversation! Your thoughts help the community grow.
Join to leave a comment
Members earn 10 SHARP for a comment, 10 SHARP for a reaction, and 250 SHARP for every blog they publish.
Join the conversation! Your thoughts help the community grow.