I love the null-coalescing operator because it makes it easy to assign a default value for nullable types.
int y = x ?? -1;
That's great, except if I need to do something simple with x
. For instance, if I want to check Session
, then I usually end up having to write something more verbose.
I wish I could do this:
string y = Session["key"].ToString() ?? "none";
But you can't because the .ToString()
gets called before the null check so it fails if Session["key"]
is null. I end up doing this:
string y = Session["key"] == null ? "none" : Session["key"].ToString();
It works and is better, in my opinion, than the three-line alternative:
string y = "none";
if (Session["key"] != null)
y = Session["key"].ToString();
Even though that works I am still curious if there is a better way. It seems no matter what I always have to reference Session["key"]
twice; once for the check, and again for the assignment. Any ideas?
You could also use
as
, which yieldsnull
if the conversion fails:This would return
"none"
even if someone stuffed anint
inSession["key"]
.If you're frequently doing this specifically with
ToString()
then you could write an extension method:Or a method taking a default, of course:
If it will always be a
string
, you can cast:This has the advantage of complaining instead of hiding the mistake if someone stuffs an
int
or something inSession["key"]
. ;)All of the suggested solutions are good, and answer the question; so this is just to extend on it slightly. Currently the majority of answers only deal with null validation and string types. You could extend the
StateBag
object to include a genericGetValueOrDefault
method, similar to the answer posted by Jon Skeet.A simple generic extension method that accepts a string as a key, and then type checks the session object. If the object is null or not the same type, the default is returned, otherwise the session value is returned strongly typed.
Something like this
create an auxiliary function
Skeet's answer is the best - in particularly I think his
ToStringOrNull()
is quite elegant and suits your need best. I wanted to add one more option to the list of extension methods:Return original object or default string value for null:
Use
var
for the returned value as it will come back as the original input's type, only as the default string whennull