System.NullReferenceException in both cases when checking context.Request.Path - c#

try
{
if (context.Request.Path != null) // this will throw NullReferenceException exception.
{
}
}
catch (System.NullReferenceException)
{
if (context.Request.Path == null) //System.NullReferenceException: 'Object reference not set to an instance of an object.'
{
}
}
I'm trying to check the value of context.Request.Path. The issue here is that I'm having System.NullReferenceException in both cases when checking context.Request.Path.
context is of type HttpContext

The problem is not that the Path is null. The problem is that either context or context.Request is null. You could use null propagation to check:
if (context?.Request?.Path != null)
{
}

Related

Possible null reference after null check

I have a problem resolving this CS8603 warning. Even though there is a null-check for resource variable, null reference is still possible. How come?
Code:
public string GetResource(string resourcePath)
{
var resource = Application.Current.Resources[resourcePath];
if (resource == null)
{
return $"{ResourceError} [{resourcePath}]";
}
// ToDo: CS8603
return resource.ToString();
}
You did correctly check wether resource is null. But even if it is not, ToString() might return null. You can use something like
return resource.ToString() ?? "";

Differences in null declaration

Take the following:
obj myVar;
and
obj myVar = null;
Is there an actual difference between these two - and are they both caught by (myVar == null)?
Your answer is in your question. obj != null means "the object exists".
However, this is only true almost all the time. A custom override of the == and != operator can change this functionality, so to be absolutely sure you can use !Object.ReferenceEquals(obj,null) to ensure that the object does exist, in all cases.
The error you are getting is a System.NullReferenceException, and will always be averted by this check.
The short, but sweet, answer is: the check (object != null) always prevents object not set to an instance
Worth mentioning
If you are reading objects from a database like in the snippet of code below:
private object GetItem(DataSet dataSet1, string tableName, int row, int col) {
object obj = null;
try {
obj = dataSet1.Tables[tableName].Rows[row][col];
} catch (Exception err) {
Console.WriteLine(err.Message);
}
return obj;
}
The returned value could be null (if an exception were caught) or DBNull.Value if dataSet1.Tables[tableName].Rows[row][col] was not set in the database.
If, however, you neglect to initialize object obj as in the example below:
private object Test2(DataSet dataSet1) {
object obj;
try {
obj = dataSet1.Tables[0].Rows[0][0];
} catch (Exception err) {
Console.WriteLine(err.Message);
}
return obj;
}
The code will not compile under Visual Studio.
That is the same thing. If an object is not set to an instance of an object, it will have not have a reference to anything, and will in other words, be null.

Null reference Exception unhandled by the user code

I build my solution in visual studio(successfull) and I am trying to run it but for some reason at the following line of code it was throwing the exception I went several articles but there was no exact solution how this could be handled
public static int GetCurrentPolicyClassId()
{
**int policyClassId = (int) HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID];**
return policyClassId;
}
One of the values in the chain you've called is null. You just need to check before getting the values:
if(HttpContext != null &&
HttpContext.Current != null &&
HttpContext.Current.Session != null &&
HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID] != null)
{
// Get the value here.
}
else
{
// Something was null. Either set a default value or throw an Exception
}
You should probably check if HttpContext != null && HttpContext.Current != null && HttpContext.Current.Session != null
any exception is handled by try/catch (or finally), if that exception is possible to handle in general.
For example StackOverflowException could not be handled.
You need to:
what type of exception is
understand reasons of it
based on this decide if that exception is an exceptional behaviour in your application
if yes, handle it with try/catch if program needs to handle it, or leav program to fail, as the exception recieved is too dangerous and it's better to let to fail everything.
if this is not exceptional behavior, try to handle it with, for example null checks, or whatever...
Hope this helps.

Can't find why do I have a null reference exception

Below is the code and the problematic line.
When I hover with the mouse on src.EnergyServiceLevel, it shows that it's null.
How can that be if I'm checking for null in the previous line?
My guess was that maybe there are threads that making the problem so I've add a lock,
but it didn't helped.
public static ServiceLevelsGroup SafeClone(this ServiceLevelsGroup src) {
ServiceLevelsGroup res = null;
lock (_locker) {
if (src != null) {
res = new ServiceLevelsGroup();
if (src.EnergyServiceLevel != null) {
res.EnergyServiceLevel = new ServiceLevelInfo { ServiceGrade = src.EnergyServiceLevel.ServiceGrade };
if (src.EnergyServiceLevel.Reason != null)
res.EnergyServiceLevel.Reason = src.EnergyServiceLevel.Reason;
}
}
}
return res;
}
The exception occurs at the res.EnergyServiceLevel = ... line in the above code.
Here's a screenshot of the exception occurring in debug mode:
Your code shows lock(_locker) - so it looks like you're in a multithreaded environment. Can you check that nothing else is NULLing your variable? i.e. that everything else is also calling lock(_locker) correctly?
Maybe your NULL is at res.EnergyServiceLevel.
src.EnergyServiceLevel.ServiceGrade may be null
Moving mouse pointer to each reference will exactly show you which is null.

fix System.NullReferenceException in C#

i m developing a website and stuck with System.NullReferenceException .
on the master page I m using this code
if (Request.Url.ToString().ToLower().Contains("content.aspx"))
{
if (Request.Params["ModuleID"].ToString() == null)
{
Response.Redirect("Content.aspx?ModuleID=1");
}
}
when Module Id is blank then it creates null reference exception.
Just take out the call to ToString():
if (Request.Params["ModuleID"] == null)
{
Response.Redirect("Content.aspx?ModuleID=1");
}
Currently you're trying to call ToString on a null reference.
This won't redirect if the ModuleID is present but empty though. You may want:
if (string.IsNullOrEmpty(Request.Params["ModuleID"]))
{
Response.Redirect("Content.aspx?ModuleID=1");
}
You have to check the Request.Params["ModuleID"] on null. An null does not have a .ToString(), that is why you get this exception.
If you use the following code you should not get an NullReferenceException.
if (Request.Url.ToString().ToLower().Contains("content.aspx"))
{
if (Request.Params["ModuleID"] == null)
{
Response.Redirect("Content.aspx?ModuleID=1");
}
}

Categories

Resources