How to Update Session Object in C#

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 Employee Class as mentioned under

public class Employee
{
public string Emp_FName { get; set; }
        public string Emp_LName { get; set; }
}

 Problem:

Employee objemployee = new Employee();
objemployee.Emp_FName = "Sachin";
objemployee.Emp_LName = "Tendulkar";

Then try to save object in Session
Session["EmployeeObj"] = objEmployee;

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,

employee newemployee = new employee(); //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 in class.
In above class create a method clone, to support copy of session.

public class Employee{

public string Emp_FName { get; set; }
public string Emp_LName { get; set; }


public Member clone()
{
Employee cloneEmployee = new Employee();
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
Ebook Download
View all
Learn
View all