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
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With