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;
}
Related
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.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
(Starred out sensitive details for obvious reasons)
The problem line of code is :
int val = (int)user.Properties["userAccountControl"].Value;
I tried instantiating int val before the try catch, but that doesn't seem to do it. I am guessing that I am incorrectly converting the userAccountControl value to an int that's why it is outputting it as a null value. I have tried moving the (int) function around the line.
I also tried adding parenthesis around the whole thing :
((int)user.Properties["userAccountControl"].Value);
The disable function :
public void Disable(string userDn)
{
try
{
DirectoryEntry user = new DirectoryEntry(userDn);
user.Path = "LDAP://******";
user.Username = #"********";
user.Password = "*******";
int val = (int)user.Properties["userAccountControl"].Value;
user.Properties["userAccountControl"].Value = val | 0x2;
user.CommitChanges();
user.Close();
}
catch (System.DirectoryServices.DirectoryServicesCOMException E)
{
MessageBox.Show(E.Message.ToString());
}
}
This is the userDn string and how I run the Disable function:
Disable("CN=Bob Ross,OU=***,DC=***,DC=***");
Debug error message :
Any help would be much appreciated
Thank you
Without more data, best guess - something is not where it supposed to be or cast failed.
A - string userDn was null and constructor of DirectoryEntry throw
B - constructor did not fail, but something in the (int)user.Properties["userAccountControl"].Value; chain was null.
I would say for start check those 2 options. For 'B', maybe try some checks, like var value = Int.TryParse(user.Properties["userAccountControl"]?.Value , out var result) ? result : throw new... / return -1 / handle error etc
Posted by mobile, sorry for formatting.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
So i know this is a common problem but the solutions ive seen are not working for me, Sorry if i havent given enough information. Line 31 is where the error happens according to unity. Here is the code
using UnityEngine;
using UnityEngine.UI;
public class Scoring : MonoBehaviour
public Text Score1;
private int scorePoint1;
// Update is called once per frame
void Start()
{
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == ("WallLeft"))
{
scorePoint1 += 1;
Debug.Log("ScorePoint");
}
}
void Update()
{
Score1 = GetComponent<Text>();
Score1.text = "" + scorePoint1.ToString();
}
}
I have tried multiple answers and it seems like everything is connected UI wise (I have tested it with different stuff and it worked) its just this is not working. Im almost it is the scorePoint1 variable that is causing it as i have done it with other variables and it worked but as soon as i switched it out for that it no longer worked. Thanks for the help!
Quick edit: i did a null check as told to on the lines and i confirmed Score1.text = "" + scorePoint1.ToString() ?? string.Empty; this line is what is causing it. Still unsure how to fix it but atleast i know this for certain
From your code any of these expressions can be the cause of the problem:
if (col.gameObject.name == ("WallLeft"))
Score1.text = "" + scorePoint1.ToString();
Debug your code and you will find there's a null check needed in one of those 3 places.
Also as a separate note:
"" + scorePoint1.ToString();
This will potentially allocate 3 strings in memory. First an empty string and then the scorePoint1 as string and then third string where the 2 values are concatenated together.
This is very bad for performance especially in a game or in a loop. If you want a string that is never null, do this instead. That will be 3 times more memory efficient:
scorePoint1?.ToString() ?? string.Empty;
Ad1:
Score1.text = "" + scorePoint1.ToString() ?? string.Empty;
The ?? is null coalescing.
= If left side is null, use right side instead.
But that is not your problem, you can't call ToString() on a null object.
In my example I use the ?. null-conditional.
= If left side is null, don't call the method/property after ?. and return null.
This is what you want, it will never fail even if there's null.
Score1.text = scorePoint1?.ToString() ?? string.Empty;
So you can see if scorePoint1 is null, ToString() is never called and prevents your error. The expression scorePoint1?.ToString() returns null, which is handled by the null coalesce and gets replaced by string.Empty.
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;
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)