Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the conditional operator ? to check for 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 isn't to cast to Boolean, then check if its true or false.

I'm trying to avoid nested if statements and figured there would be a more elegant way to do it. I'm therefore only interested in answers that contain the conditional ? operator.

Any tips?

like image 965
m.edmondson Avatar asked Dec 05 '25 07:12

m.edmondson


2 Answers

Why do you use ss variable?

What about this:

if (HttpContext.Current.Session["pdfDocument"] != null)
{
    Label1.Text = (String)Session["docName"];
}
like image 163
bniwredyc Avatar answered Dec 07 '25 20:12

bniwredyc


    object ss = HttpContext.Current.Session["pdfDocument"] ?? false; 
    if ((Boolean)ss) 
    { 
        Label1.Text = (String)Session["docName"]; 
    } 
like image 23
Akash Kava Avatar answered Dec 07 '25 19:12

Akash Kava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!