Saving an array in Session in C#

I have an array that I need to save and retrieve as a session variable.

I initialize and save the array as follows:  
    g_Move_Direction= new int[40];
    for (i=0; i<40; i++)
        {g_Move_Direction[i] =2;}
    this.Session["Move_Direction"]=g_Move_Direction;

Later I retrieve the array as follows:
    int[] g_Move_Direction = (int[]) this.Session["Move_Direction"];
   
When I try and save a new value to the array using,      
     g_Move_Direction[g_segment_count]= Convert.ToInt32(this.radio_Direction.SelectedValue);

I get the following error page: [Note I've verified that radio_Direction.SelectedValue is 1 when attempting to save the new value.]
*******************************************************************************************
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 411:      segment_type=this.radio_SegmentType.SelectedValue;
Line 412:      //Save segment type, move direction & axis
Line 413:      g_Move_Direction[g_segment_count]= Convert.ToInt32(this.radio_Direction.SelectedValue);
Line 414:      g_Segment_Type[g_segment_count]=segment_type;
Line 415:      g_Segment_Axis[g_segment_count]=this.ddlAxialForceDirection.SelectedValue;
 
Source File: c:\vsprojects\manhattanapps\actuatordesignersolution\actuatordesigner\complex_move.aspx.cs    Line: 413
Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   Actuator1.Complex_Move.btnSaveSegment_Click(Object sender, EventArgs e) in c:\vsprojects\manhattanapps\actuatordesignersolution\actuatordesigner\complex_move.aspx.cs:413
   System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   System.Web.UI.Page.ProcessRequestMain()

 *******************************************************************************************

Am I saving/retrieving it correctly?

RosanneParnellAsked:
Who is Participating?
 
vigridConnect With a Mentor Commented:
I think I made a little mistake here and maybe some of the fully-qualified variable names won't match the ones you have in your code, but I hope that the concept of scope is much clearer for you. Just to be sure:

namespace MyNamespace
{
  class MyClass
  {
    private int myVariable = 1;

    public void Test1()
    {
      Console.WriteLine(myVariable);
    }

    public void Test2()
    {
      int myVariable = 2;
      Console.WriteLine(myVariable);
    }

    public static void Main()
    {
      Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
      Test2(); // will write 2 (MyNamespace.MyClass.Test2.myVariable)
      Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
    }
  }
}

After the call to the Test2 method, that method worked on its own myVariable variable and changed that variable's value, not the one declared in the class.
0
 
vigridCommented:
Please review and check if these are not null while reading from session:
g_Move_Direction,
g_segment_count

Tell me the exact values these have in line 413 in file "complex_move.aspx.cs" and tell me their exact types too.
0
 
RosanneParnellAuthor Commented:
g_Move_Direction is of type int[40] and at this point  has <undefined value> in the watch list

g_segment_count is of type int and has the value of 0 (zero).
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
vigridCommented:
It seems that something happened with the g_Move_Direction meanwhile. Please check if you really got it back correct in line:

int[] g_Move_Direction = (int[]) this.Session["Move_Direction"];

Another thing that pops into my mind is that you can have another variable declared in another scope and you use two different variables, no matter that they have same names?
0
 
RosanneParnellAuthor Commented:
I'm new to .Net and C# so the scope is a bit confusing to me right now.

I have g_Move_Direction declared here:
namespace Actuator1
{
      /// <summary>
      /// Summary description for Complex_Move.
      /// </summary>
      public class Complex_Move : System.Web.UI.Page
      {
                   protected System.Web.UI.HtmlControls.HtmlForm Form1;
                   .
                   .
                   .
                   int[] g_Move_Direction;

and then in the Page_Load routine (for the first time through the page only - postback=false) I initialize it and save it:
    g_Move_Direction= new int[40];
    for (i=0; i<40; i++)
        {g_Move_Direction[i] =2;}
    this.Session["Move_Direction"]=g_Move_Direction;


on a post back to the page I retrieve it using:
  int[] g_Move_Direction = (int[]) this.Session["Move_Direction"];

Upon retrieving it (prior to attempting to store a value in it) I did confirm that the array is still set to all 2's.
0
 
RosanneParnellAuthor Commented:
Am I defining this variable (g_Move_Direction) in the wrong spot and then the code doesn't see it in the page functions?
0
 
vigridConnect With a Mentor Commented:
Yep, you made a mistake. You declared the variable again so it put the old variable out of scope:

Think of your variable (field) in the class as:
Actuator1.Complex_Move.g_Move_Direction - you declared it in the class

And about the variable you declared in method as:
Actuator1.Complex_Move.Page_Load.g_Move_Direction

As you can see these two are different, but C# sees the one you have declared in the Page_Load method as the g_Move_Direction. So it's considering the scope.

What you need to do is to get rid of "int[]" in front of the line you read the variables from session:
g_Move_Direction = (int[]) this.Session["Move_Direction"];

You only need to do that, because you already have declared the array in the class.

BTW, please take a look on some .NET and C# coding and naming conventions. They will help you in the future. I guess that the "g_" prefix was supposed to mean "global", and that is an obsolete term in C#. Another very nice tool that will help you maintain your code high quality is FxCop (http://www.gotdotnet.com/team/fxcop/).

HTH
0
 
vigridCommented:
And if you would add another method:

public void Test3()
{
  myVariable = 3;
  Console.WriteLine(myVariable);
}

and changed the Main:

public static void Main()
{
  Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
  Test2(); // will write 2 (MyNamespace.MyClass.Test2.myVariable)
  Test1(); // will write 1 (MyNamespace.MyClass.myVariable)
  Test3(); // will write 3 (MyNamespace.MyClass.myVariable!!!, because no variable of the same name is declared)
  Test1(); // will write 3 (MyNamespace.MyClass.myVariable)
}
0
 
RosanneParnellAuthor Commented:
Thanks! That works!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.