Checking session if empty or not

痞子三分冷 提交于 2019-11-30 03:00:41

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 (HttpContext.Current.Session["emp_num"] != null)
{
     // code if session is not null
}
  • if at all above fails.

You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.

I'd go with your first example - but you could make it slightly more "elegant".

There are a couple of ways, but the ones that springs to mind are:

if (Session["emp_num"] is string)
{
}

or

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

This will return null if the variable doesn't exist or isn't a string.

Peter

You should first check if Session["emp_num"] exists in the session.

You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])

Chandan Kumar

If It is simple Seesion you can apply Null Check using if(Session["Session_name"] !=null)

but if it is a session of a list then You need to apply Either 1 or 2

Option 1:

    if (((List<int>)(Session["Session_name"])) != null && 
       (List<int>)Session["Session_name"])).Count > 0)

Option 2:

List<int> val= Session["Session_name"] as List<int>`;`//Get the value`
if (val.FirstOrDefault() != null)

Check if the session is empty or not in C# MVC Version Lower than 5.

if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
    //cast it and use it
    //business logic
}

Check if the session is empty or not in C# MVC Version Above 5.

if(Session["emp_num"] != null)
{
    //cast it and use it
    //business logic
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!