2

I have been reading a xls file using ExcelDataReader and putting the complete DataTable in Session variable with following code

DataSet result = excelReader.AsDataSet(true,Convert.ToInt32(e.Parameter), 20);                
if (result.Tables.Count > 0)
   {                  
       if (result.Tables[0].Rows.Count > 0)
         {                       
            Session["CellDirData"] = result.Tables[0]; 
         }
   }

In some other function i am getting this DataTable from Session Variable using following code

 DataTable dtTemp = (DataTable) Session["CellDirData"];                                   
 dtTemp.Rows.RemoveAt(0); // Removing first row from local variable dtTemp

When i am removing first row from local variable dtTemp, it also update the Session variable ie now both dtTemp and Session["CellDirData"] has 19 rows.

My question is why Session get update while i am playing with local variable only ?

Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83
  • Check order of events and where all places you are setting session. – Amit Jan 07 '15 at 11:13
  • Please read on http://www.albahari.com/valuevsreftypes.aspx If you need a copy use [DataTable.Copy](http://msdn.microsoft.com/en-us/library/system.data.datatable.copy%28v=vs.110%29.aspx) – Sriram Sakthivel Jan 07 '15 at 11:13
  • @SriramSakthivel welcome your suggestion. But here i am not setting session variable which may cause updation due to change in reference variable. I am getting the session into local variable. – Rajeev Kumar Jan 07 '15 at 11:16
  • 1
    `DataTable` is a class (reference type), which means that it will be copied by reference. So if you update one, you're actually modifying the original reference. Please read the differences between value types and reference types. Everything will be clear. – Sriram Sakthivel Jan 07 '15 at 11:18

1 Answers1

2

Because default session state mode is InProc (in-process). That is, you're creating references that point to the same DataTable object, since in-process means also in-memory.

Or in other words: your session, class fields and local variables share same sandboxed environment and memory and this means that creating new session state keys is almost the same as declaring new references (class fields and local variables).

See session state modes article on MSDN to learn more about available modes and their details.

If you want to store a session key in some state and continue editing the source object without affecting the stored one, you should serialize it to XML or JSON (or any other serialization format). See this other Q&A here on StackOverflow: How to convert datatable to json string using json.net?

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206