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?
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With