Saturday, April 8, 2017

Get Session Variable and Check for Null

Accessing a Session variable that hasn't been created causes a null exception.   You can use the C# null-coalescing(??) or 'as' operators to simplify and avoid a null exception.

First two examples yield the same result;
myClassObj will receive the myClassObj stored in the Session variable if it exists; otherwise null.

With ?? Operator

   MyClass myClassObj = (MyClass)Session["mySessionName"] ?? null;

With as Operator

   MyClass  myClassObj = Session["mySessionName"] as MyClass 


With Both Operators

   string strMyClass = Session["mSessionName"] as string ?? "";

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.