Note that there are some explanatory texts on larger screens.

plurals
  1. POChecking a function result for null values
    text
    copied!<p>In his answer to <a href="https://stackoverflow.com/questions/9788466/what-is-the-proper-way-to-check-for-null-values">this question</a>, BlackBear suggested replacing </p> <pre><code> string y = Session["key"] == null ? "none" : Session["key"].ToString(); </code></pre> <p>with</p> <pre><code> string y = (Session["key"] ?? "none").ToString(); </code></pre> <p>This works great if <code>Session["key"]</code> is a string value, but what if I want to do this with an object? For example, I could do this:</p> <pre><code> string y = GetMyObject() == null ? "none" : GetMyObject().ToString(); </code></pre> <p>But what if I don't want to evaluate <code>GetMyObject()</code> twice? Is my only choice to store the results in a variable, then check that variable for null?</p> <pre><code> var x = GetMyObject(); string y = (x == null) ? "none" : x.ToString(); </code></pre> <hr> <p>Edit: This is all theoretical - I've run into it before, but I don't have a specific example in front of me right now. That being said, here's an example class.</p> <pre><code>class MyObject { private MyObject() { } public MyObject GetMyObject() { return new MyObject(); } public override string ToString() { return "A String"; } } </code></pre> <p>If I do <code>string y = (GetMyObject() ?? "none").ToString();</code>, I get </p> <blockquote> <p>Operator '??' cannot be applied to operands of type 'MyObject' and 'string'".</p> </blockquote> <p>Ideally, I'd be able to do </p> <pre><code> string y = GetMyObject().ToString() ?? "none"; </code></pre> <p>and have it work even if GetMyObject() is null. Basically null-coalescing operator acting as a self-contained <code>try {} catch (NullReferenceException) {}</code>. I know I <em>can't</em>, but that would be the ideal.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload