开发者

How to default null session values to blank strings in C#

开发者 https://www.devze.com 2023-01-20 21:17 出处:网络
I\'m used to using VB.net for web programming. Often, I have something like: Dim s as string = Session(\"s\")

I'm used to using VB.net for web programming.

Often, I have something like:

Dim s as string = Session("s")

I get a string value for s from the web session. If there is no value in the web session, I get a blank st开发者_如何学Cring.

However, AFAIK, in C#, I have to have something like the code below to do the same thing.

string s;
try { s = Session["s"].ToString(); }
catch { s = ""; }

Is there an easier way to do this?


This is a quick way of doing this:

s = (string)Session["s"] ?? "";

This will cast Session["s"] to a string, and if it is not null, return the value. If it is null, it will return an empty string. The "a ?? b" expression is essentially the same as "a != null ? a:b" (?? is compiled more efficiently though)

Something else to keep in mind: you should never use exceptions for normal application logic.


Because string is reference type then is nullable, so you can check for empty or null by means of string.IsNullOrEmpty(s):

string s = string.IsNullOrEmpty((string)strObject) ? string.Empty : strObject.ToString();

Otherwise (as Philippe Leybaert says) you can use ?? operator.


I almost agree to Philippe, but it only works if "s" is present in the session, otherwise there will be a KeyNotFoundException. This code checks it, but does not solve the NULL issue of Philippe.

s= Session.ContainsKey("s")?Session["s"]:"";

So to cover both possibilities, it becomes mre complex:

s = Session.ContainsKey("s")?(Session["s"]??""):"";

It does not really make it easier, but the performance should be better than catching an exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消