Checking session if empty or not - c#

I want to check that session is null or empty i.e. some thing like this:
if(Session["emp_num"] != null)
{
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
}
Or just
if(Session["emp_num"] != null)
{
// The code
}
because sometimes when i check only with:
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
I face the following exception:
Null Reference exception

Use this if the session variable emp_num will store a string:
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//The code
}
If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.

if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
if at all above fails.

You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.
I'd go with your first example - but you could make it slightly more "elegant".
There are a couple of ways, but the ones that springs to mind are:
if (Session["emp_num"] is string)
{
}
or
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
}
This will return null if the variable doesn't exist or isn't a string.

You should first check if Session["emp_num"] exists in the session.
You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])

If It is simple Session you can apply NULL Check directly Session["emp_num"] != null
But if it's a session of a list Item then You need to apply any one of the following option
Option 1:
if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
{
//Your Logic here
}
Option 2:
List<int> val= Session["emp_num"] as List<int>; //Get the value from Session.
if (val.FirstOrDefault() != null)
{
//Your Logic here
}

Check if the session is empty or not in C# MVC Version Lower than 5.
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//cast it and use it
//business logic
}
Check if the session is empty or not in C# MVC Version Above 5.
if(Session["emp_num"] != null)
{
//cast it and use it
//business logic
}

Related

Excel IsError equivalent function in C#

Is there a function in c# that can help to check if the statement is going to return error.
I am aware about try{} catch{} but we can't use it in condition checking. For example:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = if(operationResult != null)
{
if(operationResult.Response != null)
{
operationResult.Response.ResponseText;
}
Else
{
"Null";
}
}
Else
{ "Null"; }
In the example above, I need to perform multiple checks to validate the operationResult object properties at multiple levels due to nested objects in it, to determine the final value I want to read and consume as server response value.
If we have some thing like IsError() function in Excel, we can simply try to read the final object property i.e. operationResult.Response.ResponseText; inside of that function and if any of the parent object is null and it has to throw an error it will return false and we can return the value from the else block as shown in the hypothetical example below:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = IsError(operationResult.Response.ResponseText)? "Null": operationResult.Response.ResponseText;
So, do we have something like this in C#? Hope this makes sense?
If you're using c# 6 or newer version then you can use null-conditional & null-coalescing-operator operator like below.
Here you need to place ? to check if object is null or not. If object is null then it will not perform any further check and return null. And null-coalescing-operator (??) will be used to check if value is null then it will return value provided afer ??.
string ServerResponse = SomeRestFunction.Trigger()?.Response?.ResponseText ?? "Null";

how to check if a hidden value is null

I have a asp.net app where I utilize hidden fields to store values (if need be).
So on the designer side I have this..
<asp:HiddenField ID="hdDDAPDischargeDate" runat="server" />
In my C# code I either assign a value to it or leave it as is, so basically something along the lines...
if ( condition.........)
{
hdDDAPDischargeDate.Value.ToString()== '10/23/2017'
}
But in many cases I don't assign a value, so later on when i go to check what the value of it is, i can't get it to hit the ELSE part of the if statement
I tried:
if (hdDDAPDischargeDate.Value != null)
if (hdDDAPDischargeDate.Value.ToString != null)
But in both cases it thinks there's a value in the field, or I'm basically checking it wrong
If i hover over the field, it simply shows ""
Hidden fields can't be null, which makes sense if you think about the way they are represented in the HTTP request.
Try checking for an empty string instead:
if (hdDDAPAdmissionDate.Value != "")
{
//Foo
}
If for some reason you don't believe me or are not sure, you can always check both:
if (hdDDAPAdmissionDate.Value != null && hdDDAPAdmissionDate.Value != "")
{
//Foo
}
Or better yet:
if (!string.IsNullOrEmpty(hdDDAPAdmissionDate.Value))
{
//Foo
}

Get Object Reference Error when trying to use Request.QueryString [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have a page.aspx that reads the query string, and if the QueryString is something like page.aspx?id=1, it runs some code.
However, I want it to simply ignore that code if no QueryString is specified. If I simply go to page.aspx. Right now, the only code I have on page load is
if (Request.QueryString["id"].Equals("1"))
{
//Do something
}
That works if I go to page.aspx?id=1. However, simply going to page.aspx gives me this error:
object reference not set to an instance of an object
How can I load the page with no query string?
You need to check for nulls
if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
//Do something
}
You can do this:
if(Request.QueryString.Length != 0)
{
...
}
If you try to access elements which are not present, you'll receive an exception. So, since QueryString has a property of Length, checking it against 0 means there is no query string at all.
Else if you want to know that only if id key isn't present, you can do this:
if(Request.QueryString.AllKeys.Contains("id"))
{
}
Try this:
if (Request.QueryString["id"] != null && Request.QueryString["id"].Equals("1"))
{
//Do something
}
Another way :
string id = Request.QueryString["id"] ?? "";
if(id == "1")
{
//Do something
}
This will cover any null reference issues or when there simply is an empty query string
if (Request.QueryString != null && Request.QueryString["id"] != null && Request.QueryString["id"] == "1")
{
//do work
}
Whenever you see this error :
object reference not set to an instance of an object
Know that you are checking for something that is null or simply doesn't exist
so try this :
if(Request.QueryString["id"] != null)
{
if (Request.QueryString["id"].Equals("1"))
{
//Do something
}
}

How can I pass args that are sometimes null?

In this event handler:
public static void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
DateTimeOffset timeStampUTC = args.Position.Coordinate.Timestamp.ToUniversalTime();
DateTimeOffset timeStampLocal = timeStampUTC.LocalDateTime;
DateTimeOffset dateTimeStampUTC = timeStampUTC.DateTime;
RecordLocation(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude,
args.Position.CivicAddress.City, args.Position.CivicAddress.State, dateTimeStampUTC, timeStampLocal);
}
...I'm getting a Null Reference Exception because args.Position.CivicAddress is null (the rest of the args passed to RecordLocation() are valid). I reckon sometimes Position will be null, and sometimes it won't. What can I do to let the times when no City or State is found pass through unabated? I tried to make those strings in RecordLocation()'s definition nullable, but that won't compile.
Do I need to check CivicAddress for null and create an overloaded version of my RecordLocation() method, or is there another way to handle this?
What can I do to let the times when no City or State is found pass through unabated?
You just need to check it. For example:
if (args.Position != null && args.Position.CivicAddress != null)
{
// Now you can use args.Position.CivicAddress.State safely
}
If you want to do lots of things with args.Position, you quite possibly want one "outer" if statement - quite possibly with a local variable to simplify things:
var position = args.Position;
if (position != null)
{
if (position.CivicAddress != null)
{
// Use properties of position.CivicAddress
}
// Assuming Coordinate is nullable to start with, of course...
if (position.Coordinate != null)
{
// ...
}
}

Inconsistent null value reference exceptions

I am facing inconsistent null value reference errors while I am trying to store my values from a serialized class object.
if ( item.current_location.city!=null )
{
var city = item.current_location.city.Select(i => i.ToString());
}
In the above code snippet, successful insertion takes place even if any index in item array has null values. But it throws exception in some cases,which I don't think can be distinguished in any manner from other cases( when the value is null)
item could be null as well
current_location could be null as well,
not only city.
This would help
if (item != null &&
item.current_location != null &&
item.current_location.city != null) {
...
}
EDIT:
Note: This code works, since c# implements a so-called shortcut-evaluation of Boolean expressions. If item should be null, the rest of the expression would not be evaluated. If item.current_location should be null, the last term would not be evaluated.
(I do not see any insertion in the code above.)
Starting with C#6.0 you can use the null propagation operator (?):
var city = item?.current_location?.city?.Select(i => i.ToString());
if (city != null) {
// use city ...
}
I can't give a definitive answer without seeing your dataset, but you're not checking for null values on the item object or the current_location object. I would suggest you start by changing your test to this:
if (null != item && null != item.current_location && null != item.current_location.city)
{
...
}

Categories

Resources