Clean way to catch error Object reference not set [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
When DeliveryMethodComboBox has no selectedItem, the
Object reference not set to an instance of an object.
error appears.
what is the best way to solve this?
In this example i've added a try and catch.
try
{
DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
catch
{
DeliveryMethodLabel2.Text = "";
}

I'm assuming you mean that the value is null
** Assumes you don't have nulls in your list and that you are only concerned about whether there is a selection or not.
if(DeliveryMethodComboBox.SelectedIndex != -1)
{
DeliveryMethodLabel2.Text = DeliveryMethodComboBox.SelectedItem.ToString();
}
else
{
DeliveryMethodLabel2.Text = "";
}
Otherwise, if DeliverMethodComboBox can be null, just change the if to
if(DeliveryMethodComboBox != null && DeliveryMethodComboBox.SelectedIndex != -1)

Related

I am getting "Object reference not set to an instance of an object" on DateTime pass [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed last year.
if(dates == null)
{
DateTime tempDate = WorldTimeAPI.instance.GetCurrentDateTime();
print(tempDate);
dates.SetDailyWeeklyDate(tempDate);
SaveSystem.TaskDateSave(dates);
}
the error is on third line of the block. The print is printing the date, no issues there.
the SetDailyWeeklyDates() function is below:
public void SetDailyWeeklyDate(DateTime date)
{
dailyTaskDate = date;
weeklyTaskDate = date;
}
Thoughts?
"if(dates == null)" - you only get to the code if dates is null
You either want to change the code to "if(dates != null)" or create an instance of whatever class "dates" is before the third line.

A safe way to get some deep value [duplicate]

This question already has answers here:
Elegant way to avoid NullReferenceException in C#
(4 answers)
Closed 3 years ago.
Suppose I have a fairly deep class, and I need to get some field embedded deep within
int? result = this.child.button.data;
return result;
And at any point, it could be pointing to a null, in which case I want to return null as well. A common approach would be
if (this.child != null && this.child.button!= null) {
return this.child.button.data;
} else {
return null;
}
But if the field is REALLY deep nested, then the only solution I can think of is this:
int? result = null;
try {
result = this.child.button.handler.controller.renderer.data;
} catch (NullReferenceException ex) {
// Do nothing here
}
Is this the correct approach, or is there a better solution?
you may check the null conditional operator in C# - ?.
Like:
result = this?.child?.button?.handler?.controller?.renderer?.data;

File.exists giving a null reference exception instead of returning false. c# [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
if(File.Exists(Application.persistentDataPath + "/users/" + Input.GetComponent<Text>().text + ".dat"))
This line always causes a null reference exception instead of returning false when it cannot find the file.
File.Exists is not problem. Think about fixing your code like this
if (Application.persistentDataPath != null && Input != null && Input.GetComponent<Text>() != null && Input.GetComponent<Text>().text != null)
{
if(File.Exists(Application.persistentDataPath + "/users/" + Input.GetComponent<Text>().text + ".dat"))

Null string exception [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Before i ask my question i need to mention that i looked up in the site to solve the problem but i didnt find nothing.
Here is my function :
public string GetAccessToken(int agencyId)
{
string retrunString = null;
Token fbToken = tokenMgr.Get(agencyId, "FacebookInsights");
if (String.IsNullOrWhiteSpace(fbToken.AccessToken)) **
return retrunString;
else
return fbToken.AccessToken;
}
When Token is an object which include a String field name : AccessToken.
When i debug the code and reach the line with the ' ** ' when fbToken.AccessToken is NULL , I get an exception " Object reference not set to an instance of an object."
When i looked up in other threads they suggest to use String.IsNullOrWhiteSpace , but it didnt solve the problem and i keep getting the error.
I would greatly appreciate any help , thanks in advance!
fbToken is null, not fbToken.AccessToken. Use something like this:
if ( fbToken == null || String.IsNullOrWhiteSpace(fbToken.AccessToken) )
New C# 6.0 allows you to do null propagation to accomplish this as well:
if ( String.IsNullOrWhiteSpace(fbToken?.AccessToken) )
Write it like this. Check Null-conditional Operators
if(String.IsNullOrWhiteSpace(fbToken?.AccessToken))
{
//your stuff
}
You have to validate the object fbToken and not his member AccessToken.
public string GetAccessToken(int agencyId)
{
var fbToken = tokenMgr.Get(agencyId, "FacebookInsights");
return (fbToken == null) ? null : fbToken.AccessToken;
}

Why do I get a NullReferenceException in this foreach method [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
int count = 0;
foreach (string s in Settings.Default.Name)
{
count++;
}
Settings.Default.Name[count] = tb_add_name.Text;
Settings.Default.Save();
Settings.Default.Name is an empty string array but should the foreach - method just dont start if the string array is empty instead of giving me this error?
The array will be filled with words later.
Yes, but that won't change the fact that count is still 0 and you still execute
Settings.Default.Name[count] = tb_add_name.Text;
So you should still check if the index is Valid or null. Something like:
if(Settings.Default.Name != null && Settings.Default.Name.Count > 0)
By the way, your method will always lead to an IndexOutOfRange exception because your foreach loop basically sets your count variable to the size of the Array, and Array[Array.Length] is always out of range.
You can use Array Length property.
if(Settings.Default.Name.Count > 0)
{
int count = 0;
foreach (string s in Settings.Default.Name)
{
count++;
}
Settings.Default.Name[count] = tb_add_name.Text;
Settings.Default.Save();
}

Categories

Resources