Using a conditional operator? to check for a null session variable

Take a look at this code:

System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"] ?? false;

        if ((Boolean)ss)
        {
            Label1.Text = (String)Session["docName"];
        }

Basically, I want to check if HttpContext.Current.Session ["pdfDocument"] is not null, and if it should not be added to Boolean, then check its value is true or false.

I am trying to avoid nested if statements and believe that there will be a more elegant way to do this. Therefore, I am only interested in answers containing conditional expressions? Operator.

Any tips?

+3
source share
7 answers

Why are you using the ss variable?

How about this:

if (HttpContext.Current.Session["pdfDocument"] != null)
{
    Label1.Text = (String)Session["docName"];
}
+3
source
    object ss = HttpContext.Current.Session["pdfDocument"] ?? false; 
    if ((Boolean)ss) 
    { 
        Label1.Text = (String)Session["docName"]; 
    } 
+2

, , :

System.Web.SessionState.HttpSessionState ss;

Label1.Text = (Boolean)((ss = HttpContext.Current.Session["pdfDocument"]) ?? false) ? (String)Session["docName"] : Label1.Text;

ss null, false ss "if". Label1.Text.

: , .

+1

, :

SessionState.HttpSessionState ss = false;

ifs , .

0

, , :

bool isPdfDocumentSet =
     bool.TryParse((HttpContext.Current.Session["pdfDocument"] as string, 
         out isPdfDocumentSet)
             ? isPdfDocumentSet
             : false;

EDIT: :

bool isPdfDocumentSet =
     bool.TryParse(HttpContext.Current.Session["pdfDocument"] as string, 
          out isPdfDocumentSet) && isPdfDocumentSet;
0

HttpContext.Current.Session - System.Web.SessionState.HttpSessionState, , , , , HttpSessionState "pdfDocument" .

bool "pdfDocument" , , bool null coalece it: var ss = (bool)(HttpContext.Current.Session["pdfDocument"] ?? false);.

, , - "pdfDocument" , , , : var ss = HttpContext.Current.Session["pdfDocument"] != null;.

0

, , , :

System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"];
if (ss != null)
{
    Label1.Text = (String)Session["docName"];
}
-1

Source: https://habr.com/ru/post/1769331/


All Articles