Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking session if empty or not

I want to check that session is null or empty i.e. some thing like this:

if(Session["emp_num"] != null) {     if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))             {                 //The code             } } 

Or just

 if(Session["emp_num"] != null)     {         // The code     } 

because sometimes when i check only with:

       if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))                 {                     //The code                 } 

I face the following exception:

Null Reference exception

like image 589
Anyname Donotcare Avatar asked Aug 24 '11 09:08

Anyname Donotcare


People also ask

How do I check if a session variable is empty?

If you want to check whether sessions are available, you probably want to use the session_id() function: session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

How do you check if a session has value or not?

You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.

How check session is empty in laravel?

To determine if an item is present in the session, you may use the has method. The has method returns true if the item is present and is not null. To determine if an item is present in the session, even if its value is null, you may use the exists method.


1 Answers

Use this if the session variable emp_num will store a string:

 if (!string.IsNullOrEmpty(Session["emp_num"] as string))  {                 //The code  } 

If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.

like image 175
Roy Goode Avatar answered Oct 16 '22 03:10

Roy Goode