fix System.NullReferenceException in C# - 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");
}
}

Related

System.NullReferenceException in both cases when checking context.Request.Path

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)
{
}

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() ?? "";

Why is this null check incurring a null dereference error?

So basically I want to check that a setting is not set in my C# application. The code here
if (Default["StudentAccountTypeDefault"] is null) // Crashes after this
{
//
}
else
{
//
}
seems to be crashing on the null-check. I've put a breakpoint there, and it shows Default["DefaultStudentAccountType"] to just be a blank string. Why is it crashing with a NullReferenceException? I'm pretty sure this is where it crashes-if I comment out if statement it works as expected.
Edit: To alleviate some confusion. Sooooo, Default is actually Settings.Default, and to add to that, I was actually trying to access it inside the Settings() constructor. So, before it had been initialized, obviously. Oops. "Full"-er code below.
public Settings() {
// // To add event handlers for saving and changing settings, uncomment the lines below:
//
// this.SettingChanging += this.SettingChangingEventHandler;
//
// this.SettingsSaving += this.SettingsSavingEventHandler;
//
if (Settings.Default["DefaultStudentAccountType"] is null)
{
}
else
{
}
}
You should be checking with == not with is, also depending on your data type you may need to check if Default is null too. Try this:
if(Default == null || Default["StudentAccountTypeDefault"] == null)
{
}
else
{
}
Default is a variable, so if it is null, accessing the indexer ["StudentAccountTypeDefault"] will throw a null reference exception.
If you're using a new enough .NET version, you can use:
if (Default?["StudentAccountTypeDefault"] is null)
(the null-coalescing operator). Otherwise, just check Default for null before using its indexer.

retrieving all forms from my project

I know this question has been asked before. I have the code to do this but i am getting an error and I think I know why but I am just really getting into .Net Reflection so I wish to get confirmation on whether I am correct or not.
Here is the code. I want to retrieve all the forms from my project that have a basetype of "BaseEditForm" and then all of those that end with "EditForm" I want to put in a List to populate a ListBox.
public void LoadAllEditForms()
{
formsList = new List<string>();
try
{
Assembly project = Assembly.Load("UnionAdministrator");
foreach (Type t in project.GetTypes())
{
if (t.BaseType == typeof (BaseEditForm))
{
var emptyCtor = t.GetConstructor(Type.EmptyTypes);
if (emptyCtor != null)
{
var f = (Form) emptyCtor.Invoke(new object[] {});
if (f.Name.EndsWith("EditForm"))
formsList.Add(f.Name);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am getting the error message "Object reference not set to an instance of an object." on the line
var f = (Form) emptyCtor.Invoke(new object[] {});
emptyCtor is not null and besides there is no way for emptyCtor to get to this point if it is null. So I am confused about the error message. So here is my question. For this to work properly do all my forms have to have a default constructor? Almost all my forms have a constructor that takes one or more parameters. Is that my problem?
Your code works fine.
It must be one of your constructors that throw the exception.
Check all of your derived Forms to see if any of them (those that does not take any ctor parameters) could throw a NullReferenceException if invoked.
I'm not sure why you're going through the trouble of trying to execute the constructor of every form. You could simplify your code (and avoid the whole issue) by just looking at the type names.
public void LoadAllEditForms()
{
Assembly project = Assembly.Load("UnionAdministrator");
var formsList = project.GetTypes()
.Where (t => t.BaseType == typeof(BaseEditForm) && t.Name.EndsWith("EditForm"))
.ToList();
}

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.

Categories

Resources