Checking session if empty or not

后端 未结 6 840
萌比男神i
萌比男神i 2020-12-28 13:39

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\"         


        
6条回答
  •  借酒劲吻你
    2020-12-28 14:18

    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.

提交回复
热议问题