Checking for null HttpContext.Current.Cache value - c#

In the below snippet, I am trying to assign the cache value if the cache value does not already exist. I get an Object_reference_not_set_to_an_instance_of_an_object error when running the following. What am I missing?
if (string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
HttpContext.Current.Cache[Key] = data;
I looked around on SO but couldnt find something similar. Maybe I am just not wording my problem correctly.

HttpContext.Current could be null.
HttpContext.Current.Cache[Key] could be null.
If either of those are null, it would result in the error you are getting.

You should check for null on HttpContext.Current and on HttpContext.Current.Cache[Key], both of which could be null. Here's a possible solution, as long as you're okay with not setting the cache key if HttpContext.Current is null.
if (HttpContext.Current != null &&
(HttpContext.Current.Cache[Key] == null || string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
{
HttpContext.Current.Cache[Key] = data;
}

You are getting the NullReferenceException because you are trying to call ToString() on a null instance.
You have to check if HttpContext.Current.Cache[Key] is null before calling ToString()
if (HttpContext.Current.Cache[Key] == null)
{
HttpContext.Current.Cache[Key] = data;
}

I just changed the 'get value, convert to string, compare' logic to just get the value and see if it's null right up front. Silly me.
if (HttpContext.Current.Cache[Key] == null)
HttpContext.Current.Cache[Key] = data;
The "Object_reference_not_set_to_an_instance_of_an_object error" is actually essentially the 'null' value I was looking for...

If they key isn't present, then this would return null:
HttpContext.Current.Cache[Key]
You're then blindly calling ToString() on the value from the cache, causing the exception.
You need to assign the value from the cache to a temporary variable and test it for null before calling ToString().

Related

Nulling a string or any type when don't know return value?

What is the best way to null a item if you don't know what its value can be? I am going through objects which can be of any type from an object. How can I cast when I don't know what the return value might be?
string viewValue
= emop.Object[null, viewDetails.Columns[i].Property] != null
? emop.Object[null, viewDetails.Columns[i].Property].Value.ToString()
: string.Empty;
I thought it might be better to cast all the objects as string but some items it's failing on saying item is null.
Without approving of your conversion to a string for all objects, since I don't know the data you're working on. I believe this would fix your actual error.
string viewValue
= emop.Object[null, viewDetails.Columns[i].Property] != null && emop.Object[null, viewDetails.Columns[i].Property].Value != null
? emop.Object[null, viewDetails.Columns[i].Property].Value.ToString()
: string.Empty;
I added a not null check against the .Value property. Otherwise calling .ToString() could be calling against a null object.

Object reference error on session

I am getting error:
Object reference not set to an instance of an object.
It errors when I try to get the value of a session. The value of the session is null but I have tried testing it to check if it is null and on the if statement it still always fails with this error.
string test;
if (Session["CustType"].ToString() != null ||
Session["CustType"].ToString() != String.Empty)
{
test = Session["CustType"].ToString();
txtCustomerType.Text = test;
}
The error is on the second line of this code. I just don't know what to do because I can't do anything with it if it just errors even when I tried to check whether it is empty or not.
You need to check following. Remove ToString() as calling ToString() on null gives you Object reference error.
Session["CustType"] != null
Use
(!String.IsNullOrEmpty(Session["CustType"]))
first check null, and then call ToString
var obj = Session["CustType"];
if (obj != null &&
!string.IsNullOrEmpty(obj.ToString()))
{
txtCustomerType.Text = obj.ToString();
}
To use ToString() on an object, it cannot be null. Where you have..
Session["CustType"].ToString() != null
You need to replace it with...
Session["CustType"] != null
It may be because you are referencing an object in a table that cannot be reached. Debug your code with breakpoints and check whether your test variable has a value assigned to it at the moment of the exception. If the count of the held table is 0, this will confirm that is the problem.
You should check:
Session["CustType"] != null
before using Session["CustType"].ToString() because if it is null, you are trying to call ToString() on null object.
Most concise code would be probably:
var test = Session["CustType"] as string;
if (!string.IsNullOrEmpty(test))
{
txtCustomerType.Text = test;
}
you have remove tostring() from session while checking null value
use this
if (Session["CustType"] != null &&
Session["CustType"].ToString() != string.Empty)
instead
if (Session["CustType"].ToString() != null &&
Session["CustType"].ToString() != String.Empty)

How to cater for an object which can be both null or empty

I've got an object, specifically the following:
table.ExtendedProperties["MS_Description"].Value
If there is not property, the Value is null. If there is a property, but it is empty, the Value.toString() is "".
I would thus like to create an if-statement which caters for both eventualities. This is what I've done so far:
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))
The problem is that if it is null, it is still checking the condition on the right-hand-side.
Any ideas?
You can do:
if (table.ExtendedProperties["MS_Description"] == null || string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value))
The reason your code errors is because you don't check if table.ExtendedProperties["MS_Description"].Value is null.
Thus Value is not a string, then you have to deal with all conditions:
var description = table.ExtendedProperties["MS_Description"];
if (description == null ||
description.Value == null ||
description.Value.ToString().Equals(""))
// no value
BTW your code is not quite correct
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))
Instead of checking Value for null, you are checking if table.ExtendedProperties["MS_Description"] is not null. Thats true. You go further, but if table.ExtendedProperties["MS_Description"].Value is null (you didn't check that, remember?), you will get NullReferenceException on applying ToString().
I'm not sure if you are referring to the DataTable.ExtendedProperties property or something else, but if you are, the property returns a System.Data.PropertyCollection, which inherits from System.Collections.HashTable.
Most of the methods and properties, including the indexer ("Item") being discussed here, are directly inherited from HashTable, so in general, table.ExtendedProperties[key] can return any object, including null.
Note that you can also call DataTable.ExtendedProperties.ContainsKey(object key) to determine if the PropertyCollection contains a specific key or not.
Do you know what type of object you are retrieving when you call table.ExtendedProperties["MS_Description"].Value ?
If so, there might be other properties you can use to determine whether the property has been set, etc.
Depending on what type of object table.ExtendedProperties["MS_Description"] is, you might even be able to do something like this:
if ((table.ExtendedProperties["MS_Description"] ?? "").ToString().Length == 0) {
.....
}
That would take into account all of the possibilities:
the key doesn't exist
the key exists, but the value is null
the key exists and the value is empty
as long as the table.ExtendedProperties["MS_Decription"] object returns "" when its Value property is either null or empty.
So a little more information on the object that is returned could go a long way!
string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value)
It looks like table.ExtendedProperties["MS_Description"] is never null, you should be null checking the Value property instead
string value = table.ExtendedProperties["MS_Description"].Value;
if (value == null || value.ToString().Equals(""))
// OR
if (String.IsNullOrEmpty(value))
If table.ExtendedProperties["MS_Description"] can return null, then you need
if (table.ExtendedProperties["MS_Description"] == null ||
String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() )
And since table.ExtendedProperties["MS_Description"].Value may return null, then you need
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value == null ||
String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() )

Lightswitch NullReferenceException for String in C#

I am sure this is a case of basic ignorance, but I'm trying to test a database value using code behind in a Lightswitch project.
I'm checking if a varchar(MAX) value is null
if (Order.OrderNotes.Equals(null))
{
do.something...
}
However, I get a NullReferenceException if the value is null. If a value is there I get no error. I've tried using .contains(null), .Length = 0, .ToString() = "" etc without luck. It seems that ints and dates work fine using Equals(null), but not it seems for a string.
Help!!
Assuming you're calling this from a details screen where Order != null as #DeeMac pointed out.
You can check that Order isn't null using the same code below :
if (Order.OrderNotes == null)
{
// do.something...
}
if OrderNotes is null, you can't call any method, properties or whatever using that instance
you should call
if (Order.OrderNotes == null)
of course I assume that the var Order is not itself null,
if you want to be absolutely sure you could change your test in this way
if (Order != null && Order.OrderNotes == null)
In LightSwitch, to test if a nullable property has a value or not, you can use HasValue, so:
"if Order.OrderNotes.HasValue"
If you want the value if there is one, or the default value for the property type, you can use GetValueOrDefault:
"var value = Order.OrderNotes.GetValueOrDefault"
I agree wholeheartedly with Steve that you should be doing null checking on objects (such as Order) before trying to get a value from any of that object's properties.

how can I check whether the session is exist or with empty value or null in .net c#

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}

Categories