This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have the following method:
void setTexts()
{
if (queueIn != null)
{
queueIn.text = countIn.ToString();
}
if (queueOut != null)
{
queueOut.text = waitingForPickup.ToString();
}
}
I want it to do nothing if queueIn is null, but I keep getting a null reference exception saying queueIn is null. Why is it going into the if block when queueIn is null?
EDIT: the problem disappeared when I added a Debug.Log check, so it probably hadn't saved the previous dozen times or something. Thanks for your suggestions! I'm pretty new to C#.
You need to check all object deference points. In this case, countIn could be your offender.
Here's a possible solution to remove your exception.
void setTexts(){
if (queueIn != null && countIn != null) {
queueIn.text = countIn.ToString ();
}
if (queueOut != null && waitingForPickup != null){
queueOut.text = waitingForPickup.ToString();
}
}
You are calling ToString() on countIn and waitingForPickup - you need to check them too. E.g.:
void setTexts(){
if (queueIn != null && countIn != null) {
queueIn.text = countIn.ToString();
}
if (queueOut != null && waitingForPickup != null) {
queueOut.text = waitingForPickup.ToString();
}
}
Related
This question already has answers here:
C# null check chain in method call
(4 answers)
Closed 2 years ago.
I have just started learning C#. I'm making a game mod for Rimworld and cannot modify the pawn code. Apparently, any of the chained objects may be null. Is there a better way to bail out of the method than what I've done?
Thank you.
private void cleanseParadoxicalMemories(Pawn pawn, Dictionary<string, string> knownPawnIDs)
{
if (pawn.needs == null || pawn.needs.mood == null || pawn.needs.mood.thoughts == null || pawn.needs.mood.thoughts.memories == null)
{
return;
}
// Remove any crazy-making memories from a now-invalid timeline due to traveling across an Einstein-Rosen bridge
// (basically, selective amnesia about everyone not going with us.)
foreach (var paradox in pawn.needs.mood.thoughts.memories.Memories.ToList())
{
if (paradox.otherPawn != null)
{
pawn.needs.mood.thoughts.memories.RemoveMemory(paradox);
}
}
}
You can use null conditional operator ?. to achieve this :
private void cleanseParadoxicalMemories(Pawn pawn, Dictionary<string, string> knownPawnIDs)
{
if (pawn?.needs?.mood?.thoughts?.memories == null)
{
return;
}
// Remove any crazy-making memories from a now-invalid timeline due to traveling across an Einstein-Rosen bridge
// (basically, selective amnesia about everyone not going with us.)
foreach (var paradox in pawn.needs.mood.thoughts.memories.Memories.ToList())
{
if (paradox.otherPawn != null)
{
pawn.needs.mood.thoughts.memories.RemoveMemory(paradox);
}
}
throught my app I've seen too many not equal null checks, which looks like this:
if (receivedRequest != null && receivedRequest.Status != null)
Is there cleaner way to write things like this?
Sure, since C# 6 you can use null propagation... something like this:
if (receivedRequest?.Status != null)
Check out this blog post with additional details...
It is possible to create un check method:
private bool CheckReceivedRequest()
{
return receivedRequest != null && receivedRequest.Status != null;
}
Used like that:
if ( CheckReceivedRequest() )
{
}
If receivedRequest.Status is not null, you don't need to check if receivedRequest is null.
if (receivedRequest.Status != null)
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I've added a null property check to a boolean method, to prevent returning true, if any string fields are empty in a SelectedCustomer property.
The problem is my bool method gets called from the constructor, before I've input any data into the SelectedCustomer model. This then causes a Null reference exception.
I can see from the breakpoint I set on the statement that, "{"Object reference not set to an instance of an object."}" is the error. The selectedCustomer property isn't initialized until I select a customer from a data grid.
My question is, how can I perform the null check in this manner without causing a NRE?
This is the CanModifyCustomer boolean method where I perform the null check:
private bool CanModifyCustomer(object obj)
{
if (SelectedCustomer.FirstName != null && SelectedCustomer.LastName != null && SelectedCustomer != null)
{
return true;
}
return false;
}
It is passed as a param in my buttons command:
public MainViewModel(ICustomerDataService customerDataService)
{
this._customerDataService = customerDataService;
QueryDataFromPersistence();
UpdateCommand = new CustomCommand((c) => UpdateCustomerAsync(c).FireAndLogErrors(), CanModifyCustomer);
}
And this is the SelectedCustomer property that the null check is preformed on:
private CustomerModel selectedCustomer;
public CustomerModel SelectedCustomer
{
get
{
return selectedCustomer;
}
set
{
selectedCustomer = value;
RaisePropertyChanged("SelectedCustomer");
}
}
Just use null conditional operator. (C#6)
if (SelectedCustomer?.FirstName != null && SelectedCustomer.LastName != null)
{
return true;
}
Or you should put SelectedCustomer != null at first. because the condition is evaluated from left to right. so if first one is false because of using && operator it will not continue to check the other parts and the condition becomes false.
if (SelectedCustomer != null && SelectedCustomer.FirstName != null && SelectedCustomer.LastName != null)
{
return true;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
This falls over on the first elseif. Basically I have a load of dropdowns and I'm trying to work out which filters to select based on if people have selected the dropdown items or not.
An unhandled exception of type 'System.NullReferenceException' occurred in
Based On
private void btnSearch_Click(object sender, EventArgs e)
{
if (ddCompany.SelectedItem.ToString() == null && ddStatus.SelectedItem.ToString() == null)
{
UpdateTicketsList("NO", "NO");
}
else if (ddCompany.SelectedItem.ToString() != null && ddStatus.SelectedItem.ToString() == null)
{
UpdateTicketsList(ddCompany.SelectedItem.ToString(), "NO");
}
else if (ddCompany.SelectedItem.ToString() == null && ddStatus.SelectedItem.ToString() != null)
{
UpdateTicketsList("NO", ddStatus.SelectedItem.ToString());
}
}
Calling ToString on a null object will result in a NullReferenceException.
Remove the calls to ToString in your if-statement expression and your code should work as expected :)
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
}
}