To Check Session is null or not

use*_*909 0 c# asp.net session-variables

In the below code I have Session variable in which I want to check whether it is null or not. Please help me to do this. (SearchDoc) is class.

var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;

if (SearchDoc == null)
{

}
Run Code Online (Sandbox Code Playgroud)

Roy*_*mir 5

This is the safest approach :

 if ((HttpContext.Current.Session !=null && Session["Documentname"] as SearchDoc!= null))
{

 //do what you want with
  ((SearchDoc)Session["Documentname"])

}
Run Code Online (Sandbox Code Playgroud)

2 things to notice :

  • Yes , sometime the session object is null. ( probably occurs with AShX's without appropriate interface)
  • use the AS operator. - once it's ok , you can safely cast to SearchDOC