6

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?

Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • 1
    In VB, you get Nothing if you attempt to retrieve a session variable that does not exist. Most of my session retrieval code looks like: Dim s As String = Session("S") If Not String.IsNullOrEmpty(s) Then DoSomethingWithS(s) End If – Jason Berkan Oct 20 '10 at 20:24

3 Answers3

16

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.

Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
  • Short, sweet. No additional functions. I like it. – NotMe Oct 20 '10 at 20:06
  • The following syntax may be cleaner: String Test = (Session["Test"] ?? String.Empty).ToString(); –  Oct 20 '10 at 20:07
  • It's not cleaner, but it is safer if Session["Test"] is not a string (which I believe is not the case here) – Philippe Leybaert Oct 20 '10 at 20:10
  • As a side note, I tend to use String.Empty instead of "". Seems more readable. – NotMe Oct 20 '10 at 20:12
  • There's no longer any benefit in that. "" is just as efficient as String.Empty. See also http://stackoverflow.com/questions/151472/what-is-the-difference-between-string-empty-and – Philippe Leybaert Oct 20 '10 at 20:15
  • @Chris: That's generally a .NET coding standard. – Steven Sudit Oct 20 '10 at 20:17
  • Phil, I'd say that if `Session["Test"]` is not a string, despite our expectations, then it's better to throw on a failed downcast than to return the `ToString` value. In short, I would not recommend Moo's code over yours. – Steven Sudit Oct 20 '10 at 20:32
  • @Steven: I agree. But it's always best to mention this "restriction" when proposing this solution of course :-) – Philippe Leybaert Oct 20 '10 at 20:35
0

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.

ArBR
  • 4,032
  • 2
  • 23
  • 29
  • String is a reference type, so it is always nullable. Your code doesn't even compile because `string?` is not valid syntax. – Philippe Leybaert Oct 21 '10 at 08:58
  • You are right Philippe, string is a reference type. I have changed my code to reflect such idea. – ArBR Oct 21 '10 at 14:53
-3

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.

  • I don't believe that it throws any such exception. The documentation (at http://msdn.microsoft.com/en-us/library/f0yd7k72.aspx) reads: "The value in the collection with the specified name. If the specified key is not found, attempting to get it returns null, and attempting to set it creates a new element using the specified key." – Steven Sudit Oct 20 '10 at 20:16
  • Indeed, Session will return null if the key is not found. It will not throw an exception – Philippe Leybaert Oct 20 '10 at 20:17
  • Yup - in the original question, it is the .ToString() call that is throwing the exception. – Jason Berkan Oct 20 '10 at 20:21