NullReferenceException changing the logic within the statement [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I have the following piece of code.
(!string.IsNullOrEmpty(billInfo.BillingMethod) || (!billInfo.BillingMethod.Equals(bill) && bill != null)
I understand that I'm getting a null reference exception because more than likely its comparing a null value within the equals method. However I'm confused on how to change the logic so I still end up with the same result without using a method.

You need to check everything that could be null. I just assume billInfo could be null too. Also The order of the statements is important here.
(billInfo != null && !string.IsNullOrEmpty(billInfo.BillingMethod) || (bill != null && !billInfo.BillingMethod?.Equals(bill))

NullReferenceException can occur if billInfo or BillingMethod is null. So first checking for billInfo not equal to null, then check for other conditions. Also, the condition after the || is the other way around. As there is no point of checking not null if the first statement is failed.
Try this instead:
if(billInfo != null && (!string.IsNullOrEmpty(billInfo.BillingMethod) ||
(bill != null && !billInfo.BillingMethod.Equals(bill)))
{
// Your code here
}

Related

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();

What is best way for object null and empty check?

I have code as below in C#:
If (this._university != Null and this._university.department !=null &&
this._university.department.class !=null &&
this._university.department.class.student != null &&
this._university.department.class.student.name != null &&
this._university.department.class.student.name.firstname != null &&
this._university.department.class.student.name.firstname !=String.empty)
{
// selecting first letter of Firstname
var F_firstname = this._university.department.class.student.name.firstname[0].tostring();
}
But the code looks very bad for checking null object.Do we have better way for null check for objects?
If you are using one of the later C# versions. Maybe this looks better with Null-conditional Operators. However, it is an unusual bit of code anyway and might point to the need to refactor a little.
var firstName = this._university?.department?.class?.student?.name?.firstname;
if(!string.IsNullOrEmpty(firstName))
{
...
}
Further Reading
Null-conditional Operators
Tests the value of the left-hand operand for null before performing a
member access (?.) or index (?[]) operation; returns null if the
left-hand operand evaluates to null.
String.IsNullOrEmpty
Indicates whether the specified string is null or an Empty string.

OR Comparison order in if statement [duplicate]

This question already has answers here:
What is the difference between the | and || or operators?
(12 answers)
Closed 4 years ago.
This may sound like a simple question but I have never used the || operator to check for NULL with another possible value. Is there a difference in how C# responds to:
if (a == "Hello" || a == null)
versus:
if (a== null || a == "Hello")
It can make a difference.
The boolean operators short-circuit. If the first part of a boolean expression can determine the result of the entire expression, it will stop there. This won't matter so much for the exact sample in the question, but imagine you have this:
if (a.property == "hello" || a == null)
If a is null, that will throw an exception. This will not:
if (a == null || a.property == "hello")
You can also use the null-conditional and null-coalescing operators:
if (a ?? "hello" == "hello")
or
if (a?.property ?? "hello" == "hello")
Is there a difference in how C# responds to ?
There is no difference in how C# responds, so order matters.
In this case, expressions are evaluated from left-to-right.
So the second one is correct one semantically and safest choice under this condition.
if (a== null || a == "Hello") //check for null first

C# nullable check optimization [duplicate]

This question already has answers here:
Deep null checking, is there a better way?
(16 answers)
Closed 5 years ago.
Can anyone tell me how do I optimize below code.
if (report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) &&
report.Breakdown[reportName.ToString()].Result != null
)
As others have mentioned, you can use the ?. operator to combine some of your null checks. However, if you're after optimizing for performance, you should avoid the double dictionary lookup (ContainsKey and index access), going for a TryGetValue instead:
MyType match = null; // adjust type
if (report?.Breakdown?.TryGetValue(reportName.ToString(), out match) == true &&
match?.Result != null)
{
// ...
}
Ayman's answer is probably the best you can do for C# 6, for before that what you have there is pretty much the best you can do if all those objects are nullable.
The only way to optimize this further is to be checking if those objects are null before even calling the code, or better yet proofing your platform so this particular function shouldn't even be called in the first place if the values are null.
If you are just getting the value from from the dictionary however you can also simplify with the null coalescing operater '??'
Example:
MyDictionary['Key'] ?? "Default Value";
Thus if the Value at that entry is null you'll get the default instead.
So if this is just a fetch I'd just go
var foo =
report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) ?
report.Breakdown[reportName.ToString()].Result ?? "Default" :
"Default";
But if you are actually doing things in the loop, then yeah you're pretty much at the best you can get there.
For C# 6 and newer, you can do it this way:
if (report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null)
You can use null conditional operator but only on C# 6
if ( report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null )
Can you try below? Also probably better to ship it to a method.
// unless report name is already a string
string reportNameString = reportName.ToString();
if ( report?.Breakdown?.ContainsKey(reportNameString) &&
report.Breakdown[reportNameString].Result != null )
{
// rest of the code
}

Bool? not nullable [duplicate]

This question already has answers here:
Why do I have to typecast an int in a ternary expression? [duplicate]
(4 answers)
Closed 5 years ago.
I have following field in my class:
public bool? EitherObject1OrObject2Exists => ((Object1 != null || Object2 != null) && !(Object1 != null && Object2 != null)) ? true : null;
But in Visual Studio I get an IntelliSense error that there cannot be a conversion between "bool" and "NULL" even though the field is nullable.
What do I do wrong?
And is there a cleaner way to check if either one of two objects is not null but one of them must be null?
try
? (bool?) true : null;
the problem is that default bool (true) is not nullable so the case statement are returning different types as far as the compiler is concerned
And you can remove the redundancy as pointed out by Servy
Object1 != null ^ Object2 != null

Categories

Resources