开发者

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


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.


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"])


If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

But if it's a session of a list Item then You need to apply any one of the following option

Option 1:

if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
 {
 //Your Logic here
 }

Option 2:

List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.

if (val.FirstOrDefault() != null)
 {
 //Your Logic here
 }


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜