Application crash after detect null variable [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I have a TreeView where I want to get NextNode so I do simple like:
var nextNode = e.Node.NextNode.Text;
If it have nextNode it returns value right. Problem if it comes null, application crash and throw
System.NullReferenceException: 'Object reference not set to an
instance of an object.'
System.Windows.Forms.TreeNode.NextNode.get returned null.
Why application crash? should not return the null variable instead application crash?

It appears that an instance of NextNode does not exist yet you attempt to access the Text property.
You have two options:
Retrieve the NextNode object and check for NULL
Use the null coalescing operator to access the text or substitute it.
1 - Check for null
NextNode node = e.Node.NextNode;
string thetext = string.Empty;
if (node != null)
thetext = node.Text
2 - Null coalescing operator
string thetext = e.Node?.NextNode?.Text ?? string.Empty;
They will both do the same thing. If NextNode is null then the variable thetext will contain an empty string, otherwise it will contain the Text of NextNode.

Related

c# dynamic variable with ?? and ? operator [duplicate]

This question already has answers here:
What does a double question mark do in C#? [duplicate]
(7 answers)
What does question mark and dot operator ?. mean in C# 6.0?
(3 answers)
Closed 2 years ago.
Sorry for asking a simple question,
I'm new to Azure Function HTTPtriggers with C#,
Anyone know what is the name = name?? data?.name; mean in c# ?
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
It essentially means
if name is not null
set name to name
else
if data is null
set name to null
else
set name to data.name
The second operator (?.) avoids a NullReferenceException by returning null instead of trying to use the access modifier. The first (??) returns the first operand if the value is not null, otherwise it returns the second.
Note that neither of these are specific to dynamic or Azure.
It could also have been written as
if ((name == null) && (data != null))
{
name = data.name;
}

Assign if not null [duplicate]

This question already has answers here:
C# 6.0 Null Propagation Operator & Property Assignment
(3 answers)
Closed 2 years ago.
Being a fan of null-coalescing operator and the null-propagating operator, I would like to assign something if the object is not null.
Something like:
myArray.FirstOrDefault()?.Value = newValue;
Instead of:
var temp = myArray.FirstOrDefault()
if(temp != null){
temp.Value = newValue;
}
Is this possible?
(I am aware I could use SetValue() )
With C# 8.0 you can do this
temp ??= newValue;

How to avoid Tostring exception if string is null? [duplicate]

This question already has answers here:
How to do ToString for a possibly null object?
(12 answers)
Closed 4 years ago.
I want to convert the data row value to sring as follows.
userGuid = dr["user_guid"].ToString();
It may contains Guid or null(Not string empty). If it contains null i got the exception.
How can i overcome this..
I guess you are reading from data reader.
You will have to check if the value is null or DBNull and then you can call to string method.
string user_guid = dr["user_guid"] != DBNull.Value && dr["user_guid"] != null ? dr["user_guid"].ToString() : null ;
Hope this helps.
if (dr[user_guid"] != null) {
//whatever you want to do
} else {
//handle the null value in some way
}
Alternatively,
dr["user_guid"]?.ToString();
The ? is what's called a "null-safe navigator".
This might be useful, one of many ways
userGuid = dr["user_guid"]?.ToString()?? "Default Value";
Please do replace "Default Value" with whatever you feel is appropriate according to your application logic.
Maybe this:
userGuid = dr["user_guid"].ToString() ?? throw new Exception();

nullable int (Int?) not throwing null reference exception [duplicate]

This question already has answers here:
Nullable ToString()
(6 answers)
Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?
(8 answers)
Closed 4 years ago.
I have encountered the code something like this
int? x = new int();
x = null;
var y = x.toString();
My understanding is that it should throw a null reference exception. But the code is not breaking and I am getting the value of y as "". Please let me understand that what's happening here in behind.
Because it is not null.
You are setting null the value of Nullable<int>, which is designed to return an empty string if the value is null.

ContainsKey is true, but still "Object reference not set to an instance of an object" [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I have such condition
// `xyz` is a `dictionary<string, MyCustomType>`.
if(smth){
xyz["ord_82"] = Func() ;// That Returns "MyCustomType" object
}
if(xyz.ContainsKey("ord_82"){
Print("started");
Print(xyz["ord_82"].ToString()); // <---------------- sometimes this line throws "Object reference not set to an instance of an object"
Print("ended");
}
I couldnt find out what could be the reason.. You see, that ContainsKey is passed, but still throws an error..
Though the key "ord_82" exists the value mapped by it can still be null. Therefore xyz["ord_82"].ToString() can still through NullReferenceException.
Use ?. operator from C# 6.0:
Print(xyz["ord_82"]?.ToString());
Notice that this will produce null for Print's argument so you can do:
Print(xyz["ord_82"]?.ToString() ?? "");
For an earlier version of C# use the ?: operator (The ?. is just a sugar syntax to it:
var value = xyz["ord_82"];
Print(value == null ? "" : value.ToString());
xyz["ord_82"] = Func() ;// That Returns "MyCustomType" object
Check if Func() is returning null object of MyCustomType
xyz["ord_82"].ToString() is called on the value returned by xyz["ord_82"] which is null and .ToString() on null will throw "Object reference not set to an instance of an object" exception which is NullReferenceException
So your code either should be changed like:
// `xyz` is a `dictionary<string, MyCustomType>`.
if(smth){
var obj = Func(); // That Returns "MyCustomType" object
if(obj != null) {
xyz["ord_82"] = obj;
}
}
or like:
MyCustomType val = null;
if(xyz.TryGetValue("ord_82", out val)){
Print("started");
Print(val.ToString());
Print("ended");
}
Corrections edited. Thanks #mjwills for the pointers

Categories

Resources