I am writing following code:
_normDoc = value as NormDoc;
if(_normDoc != null)
{
ucRusKazTextBoxesAnnotation.Controls["tbNameRu"].Text = _normDoc.AddInfoRu ?? string.Empty;
}
I think that if _normDoc.AddInfoRu == null then ucRusKazTextBoxesAnnotation.Controls["tbNameRu"].Text will be equal empty string.
But I am got error: NullReferenceException.
Can you explain me why?
PS. ucRusKazTextBoxesAnnotation not equal null;
EDIT: Sorry, I find error, yes, tbNameRu not found, because they are inside Panel control.
Make sure that ucRusKazTextBoxesAnnotation.Controls["tbNameRu"] is not null.
ucRusKazTextBoxesAnnotation.Controls["tbNameRu"] could be null just as well.
Related
I'm pretty new to C#. While attempting to set a local variable value, I'm running into a NullReferenceException.
It appears that the Buyer object is null, which I'm assuming is why it can't figure out the Buyer.Username value. What I'm not sure about is how to check if Buyer is not null AND that the Buyer.Username has a non-null value (in the most simple way possible). Unfortunately, I'm using C# 7.3 which doesn't appear to have support for the ?? operator.
BuyerUserName = string.IsNullOrEmpty(model.Transactions[i].Buyer.Username) ? "" : model.Transactions[i].Buyer.Username
Both ?? and ?. were introduced in C# 6, so you can use them:
BuyerUserName = model.Transactions[i].Buyer?.Username ?? string.Empty;
But even without that, there is nothing wrong with taking more than one line to do something, and you could just use an if statement:
var buyer = model.Transactions[i].Buyer;
if (buyer != null && buyer.Username != null)
BuyerUserName = buyer.Username;
else
BuyerUserName = string.Empty;
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have a program in which I keep getting the NullReferenceException error. Here is the code that is causing the error:
string description = "";
if (string.IsNullOrEmpty(eventItem.Description.ToString()))
{
description = "No description available.";
}
else
{
description = eventItem.Description.ToString();
}
I have looked through this post (What is a NullReferenceException and how do I fix it?), and I have tried several of the solutions (I'm afraid I simply don't understand all of them enough to try them), but I just can't figure out why this is happening. In my understanding, this error occurs because the string is in fact null.
There are events on my Google Calendar that have no description entered, so the description is null, but shouldn't the code I have check for that, and handle it? Or, is the problem that eventItem.Description.ToString() cannot be null when I call the IsNullOrEmpty method? I have also tried changing the if statement to this:
if (eventItem.Description.ToString() == null)
...but I still get the NRE error. I have tried rewriting my code so many different ways, but nothing has worked. I'm at the end of my rope!
Your eventItem itself may be null. Do something along the lines
if ( eventItem!= null && eventItem.Description != null && eventItem.Description.ToString() == null)
Updated after DStanley pointed out in the comment that .ToString() == null comparison would be unnecessary.
if ( eventItem!= null && eventItem.Description != null)
{
}
Just to help you understand a little better... NullReferenceException basically means you are trying to use some object without instantiating it. One of the simplest way to prevent is to add a null check if you are not sure whether the object is not null. And when I say adding a null check, it simply means comparing to null in the if block before accessing any property of the object.
if( objectName != null)
{
//then do something on the object
}
shouldn't the code I have check for that, and handle it?
Not if item or item.Description is null. If item is null then the call to .Description will throw a null reference exception, and if item.Description is null then the call to ToString will throw a null reference exception. There's no "magic" that lets you call ToString on a null reference.
Note that if item.Description is already a string then there's no need to call ToString(). just do:
if (string.IsNullOrEmpty(eventItem.Description))
{
description = "No description available.";
}
else
{
description = eventItem.Description;
}
Every post I have found suggests that this happens when there is a null value. I have tried examples such as one found here but no matter what I seem to try I still end up with the same error message.
Does anyone have any idea of what the case could be?
var aaresults1 = (from a in db.AAs
where a.AAID == aaid.AAID & a != null
select a);
Reading through other StackOverflow posts about this error, it appears to happen when a where clause refers to a value that is null. Based on that, I'm guessing that your aaid object is null when you run this.
var aaresults1 = db.AAs.AsQueryable();
if(aaid != null)
{
aaresults1 = aaresults1.Where(a => a.AAID == aaid.AAID);
}
In the below snippet, I am trying to assign the cache value if the cache value does not already exist. I get an Object_reference_not_set_to_an_instance_of_an_object error when running the following. What am I missing?
if (string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
HttpContext.Current.Cache[Key] = data;
I looked around on SO but couldnt find something similar. Maybe I am just not wording my problem correctly.
HttpContext.Current could be null.
HttpContext.Current.Cache[Key] could be null.
If either of those are null, it would result in the error you are getting.
You should check for null on HttpContext.Current and on HttpContext.Current.Cache[Key], both of which could be null. Here's a possible solution, as long as you're okay with not setting the cache key if HttpContext.Current is null.
if (HttpContext.Current != null &&
(HttpContext.Current.Cache[Key] == null || string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
{
HttpContext.Current.Cache[Key] = data;
}
You are getting the NullReferenceException because you are trying to call ToString() on a null instance.
You have to check if HttpContext.Current.Cache[Key] is null before calling ToString()
if (HttpContext.Current.Cache[Key] == null)
{
HttpContext.Current.Cache[Key] = data;
}
I just changed the 'get value, convert to string, compare' logic to just get the value and see if it's null right up front. Silly me.
if (HttpContext.Current.Cache[Key] == null)
HttpContext.Current.Cache[Key] = data;
The "Object_reference_not_set_to_an_instance_of_an_object error" is actually essentially the 'null' value I was looking for...
If they key isn't present, then this would return null:
HttpContext.Current.Cache[Key]
You're then blindly calling ToString() on the value from the cache, causing the exception.
You need to assign the value from the cache to a temporary variable and test it for null before calling ToString().
I am returning a scalar value from a SQL Server 2008 database:
string reason = cmd.ExecuteScalar().ToString() ?? : "";
I want to make sure that if null is returned, that reason = "" and not null.
i am getting an error on this line:
Error 3 Invalid expression term ':'
How can this be fixed?
EDIT:
thank you for the changes on the colon, now i am getting this exception on the same line:
string reason = cmd.ExecuteScalar().ToString() ?? "";
System.NullReferenceException occurred
Message="Object reference not set to an instance of an object."
Try this:
string reason = cmd.ExecuteScalar().ToString() ?? "";
BUT: this will still fail, since if .ExecuteScalar() returns a NULL, you're already causing a Null Reference Exception by calling .ToString() on that NULL value......
So I guess the ?? operator really doesn't help you here... do the "usual" dance:
object result = cmd.ExecuteScalar();
if(result != null)
{
reason = result.ToString();
}
else
{
reason = "(NULL value returned)";
}
First, you shouldn't have the : when using the ?? operator.
Second, to do what you are trying to do here without getting an error, you need to do it differently:
object objReason = cmd.ExecuteScalar();
string reason = objReason == null ? "" : objReason.ToString();
This will check whether or not your returned value is null and if it is, the second line will set reason to a blank string, otherwise it will use your returned value.
Since ExecuteScalar() returns object that might be null you should not call .ToString() since that may throw and exception.
string reason = Convert.ToString(cmd.ExecuteScalar());
This works because Convert.ToString() will convert null to string.Empty
or if you must use ?? because you really like it:
(cmd.ExecuteScalar() ?? (object)"").ToString();
Just get rid of the colon.
string reason = cmd.ExecuteScalar().ToString() ?? "";
For reference, check the MSDN page.
When using the null-coalescing operator, you don't need the colon:
string reason = cmd.ExecuteScalar().ToString() ?? "";
As others have pointed out though, ToString() would cause a NullReferenceExcpetion to be thrown anyway...so you don't gain anything here. You'd be much better off splitting this into multiple lines:
var result = cmd.ExecuteScalar();
string reason = result == null ? "" : result.ToString();
You're confusing the ? conditional operator, the syntax for which looks like this:
String x = condition ? valueIfConditionIsTrue : valueIfConditionIsFalse;
with the ?? null-coalesce operator whose syntax is as follows:
String x = possiblyNull ?? valueIfPossiblyNullIsNull;
So, apart from all that... this is the part you really want:
String reason = (cmd.ExecuteScalar() ?? "").ToString();
This takes care of your exception where ToString() was causing a null-reference exception.
Just use
string reason = cmd.ExecuteScalar() ?? "";