0

i trying to create a new Customer object and retrieve from it the Cid value like this:

Line 32:         Customer temp = new Customer();
Line 33:         temp =(Customer)Session["customer"];
Line 34:         int id = temp.Cid;

but i get this error:

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."

I also was trying to do this:

int id = Convert.Toint(temp.Cid);

but it give me the same error

John Saunders
  • 160,644
  • 26
  • 247
  • 397
shmulik hazan
  • 173
  • 2
  • 17
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Mar 11 '14 at 22:25

3 Answers3

1

This means Session["customer"] is null. You need to check if Session["customer"] is null first:

if(Session["customer"] != null){

 Customer temp =(Customer)Session["customer"];
 int id = temp.Cid;
}

If Session["customer"] is null, then you need to check to make sure you are setting Session["customer"] correctly.

If you google object reference not set to an instance of an object stack overflow you will notice that this error is asked a lot. object reference not set to an instance of an object, means exactly what it says. Session["customer"] is a session variable, which can hold a reference to an object. If you haven't set that reference, then Session["customer"] is null.

PhillyNJ
  • 3,859
  • 4
  • 38
  • 64
0

I would assign the value first and then check the value if it is null or not.

Customer temp = Session["customer"] as Customer;
if (temp != null) {
  int id = temp.Cid;
}
0

It throws the error because Session["customer"] is null. You need to make sure that Session["customer"] is not null before casting to Customer.

See SessionCustomer in the following example -

<asp:Label runat="server" ID="Label1" />
<asp:Button ID="PostBackButton" OnClick="PostBackButton_Click" 
    runat="server" Text="Post Back" />

public class Customer
{
    public int Id { get; set; }
}

public Customer SessionCustomer
{
    get
    {
        var customer = Session["Customer"] as Customer;
        return customer ?? new Customer();
    }
    set { Session["Customer"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        SessionCustomer = new Customer() {Id = 1};
    }
}

protected void PostBackButton_Click(object sender, EventArgs e)
{
    // Display the Customer ID 
    Label1.Text = SessionCustomer.Id.ToString();
}
Win
  • 61,100
  • 13
  • 102
  • 181