Turning a boolean into session variable Turning a boolean into session variable asp.net asp.net

Turning a boolean into session variable


You already have the code for setting the session variable in the comment inside the if statement:

Session["ediblesession"] = edible;

However, you probably want to set the session variable outside the if statement, so that it gets a value even if the boolean value is true.

When you want to read the value back in the other page, you will get the boolean value boxed in an object, so you would need to cast it back to a boolean value:

edible = (bool)Session["ediblesession"];

Be careful with the spelling. If you try to read a session variable with the name "ediblesesion" (as in the code in your comment), you won't get the variable that you stored as "ediblesession", and the compiler can't tell you that you made a typo as it's not an identifier.

If you want to read the value, but might come to the page without having set the value first, you would need to check if it exists:

object value = Session["ediblesession"];if (value != null) {  edible = (bool)value;} else {  edible = false; // or whatever you want to do if there is no value}


Setting:

this.Session["Edible"] = myBoolean;

Getting:

myBoolean = (bool) this.Session["Edible"];


bool? edible;object object_edible = Session["session_edible"];if (object_edible != null)    edible = object_edible  as bool?;else    edible = false;

'bool' is a non-nullable value type in c#, bool? is a nullable type