Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 string.

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?

like image 325
Vivian River Avatar asked Oct 20 '10 20:10

Vivian River


People also ask

Why is the session variable returning an empty string?

If at some point the Session variable is null then it will return a default value, which in this case is an empty string. The default can be changed depending on what the actual data type is you're working with.

How does the integration service handle null data or empty strings?

You can choose how the Integration Service handles null data or empty strings when it writes elements and attributes to an XML target file. By default, the Integration Service does not output element tags or attribute names for null values. The Integration Service outputs tags and attribute names with no content for empty strings.

Is it possible to set a string to null in C?

Terminology nitpick: strings can't be set to NULL; a C string is an array of characters that has a NUL character somewhere. Without a NUL character, it's just an array of characters and must not be passed to functions expecting (pointers to) strings. Pointers, however, are the only objects in C that can be .

How to check if a string is empty or null or not?

Now, as we are discussing Null values of C#, so one other concept that is associated with Null values is the method named IsNullOrEmpty(). This method is used when you want to check whether the given string is Empty or have a null value or not? If any string is not assigned any value, then it will have Null value.


1 Answers

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.

like image 167
Philippe Leybaert Avatar answered Sep 21 '22 11:09

Philippe Leybaert