In his answer to this question, BlackBear suggested replacing
string y = Session["key"] == null ? "none" : Session["key"].ToString();
with
string y = (Session["key"] ?? "none").ToString();
This works great if Session["key"]
is a string value, but what if I want to do this with an object? For example, I could do this:
string y = GetMyObject() == null ? "none" : GetMyObject().ToString();
But what if I don't want to evaluate GetMyObject()
twice? Is my only choice to store the results in a variable, then check that variable for null?
var x = GetMyObject();
string y = (x == null) ? "none" : x.ToString();
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.
class MyObject
{
private MyObject() { }
public MyObject GetMyObject() { return new MyObject(); }
public override string ToString() { return "A String"; }
}
If I do string y = (GetMyObject() ?? "none").ToString();
, I get
Operator '??' cannot be applied to operands of type 'MyObject' and 'string'".
Ideally, I'd be able to do
string y = GetMyObject().ToString() ?? "none";
and have it work even if GetMyObject() is null. Basically null-coalescing operator acting as a self-contained try {} catch (NullReferenceException) {}
. I know I can't, but that would be the ideal.