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
Related
This question already has answers here:
Difference between eager operation and short-circuit operation? (| versus || and & versus &&)
(7 answers)
Does the compiler continue evaluating an expression where all must be true if the first is false?
(6 answers)
Closed 3 years ago.
I'm curious about optimization opportunities by changing the order of conditions in an if statement.
Given the example below, if x is false, will the if statement try to execute the other two conditions. If it won't, should I include them in an if branch. Also at what order do they execute. Is it left to right or is it right to left?
if (x && y && z)
{
// ...
}
The check is done from left to right - if X is false, the if statement will return right away.
Think about code with null checking, for example. You would write
if(list != null && list.count > 10) {
// do something
}
but not
if(list.count > 10 && list != null) {
// the null check here does not help you
}
In c#,
if(X&y&z){}
using logical operator & always evaluates all statements.
On the contrary, if you use conditional logical operators && for conditional logical AND and || for conditional logical OR, statements are evaluated left to right and right hand statements are evaluated only if necessary.
if (x & y) {}
always evaluates both x and y, while
if (x && y) {}
Only evaluates y if x is false.
For reference check:
Microsoft .NET documentation on Boolean logical operators
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
}
This question already has answers here:
Best way to check for nullable bool in a condition expression (if ...) [closed]
(13 answers)
Closed 8 years ago.
Working with nullable bools in C# I find myself writing this pattern a lot
if(model.some_value == null || model.some_value == false)
{
// do things if some_value is not true
}
Is there a more compact way to express this statement? I can't use non-nullable bools because I can't change the model, and I can't do this
if(model.some_value != true)
{
// do things if some_value is not true
}
Because this will throw a null reference exception if model.some_value is null
One idea I had:
I could write an extension method for bools like String.IsNullOrEmpty - bool.IsNullOrFalse. This would be neat enough but I'm wondering if there's some more obvious way of doing this already?
Use a null-coalescing operator to handle cases where the value is null.
if(model.some_value ?? false != true)
{
// do things if some_value is not true
}
From msdn:
?? Operator (C# Reference)
The ?? operator is called the null-coalescing operator. It returns the
left-hand operand if the operand is not null; otherwise it returns the
right hand operand.
https://msdn.microsoft.com/en-us/library/ms173224.aspx
Alternatively, a switch would do it.
switch(model.some_value)
{
case false:
case null:
// do things if some_value is not true
break;
}
I want to say if this property is (Null OR Equals "" OR contains "ImageNotAvailable") Then go ahead and do something. But when I try to use the code below, I get an object reference error. I was hoping by putting (Publisher.ThumbnailURL == null) at the beginning of the test, the other tests would be ignored, but I get error above.
if ((Publisher.ThumbnailURL == null) | (Publisher.ThumbnailURL == "") | (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
I can simply split these up into "If Else's" but is there a way to specify that if the first test is null, don't try and figure out the rest of the If statement which will cause it to error
Use || instead of |:
if ((Publisher.ThumbnailURL == null) || (Publisher.ThumbnailURL == "") || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
|| Operator
The conditional-OR operator (||) performs a logical-OR of its bool
operands, but only evaluates its second operand if necessary.
Note that you could also use string.IsNullOrEmpty as commented by Raphaƫl Althaus:
if (string.IsNullOrEmpty(Publisher.ThumbnailURL) || Publisher.ThumbnailURL.Contains("ImageNotAvailable"))
Yep, use || to evaluate the expression as early as possible, also, using String.IsNullOrEmpty would make the statement more brief:
if (String.IsNullOrEmpty(Publisher.ThumbnailURL) || (Publisher.ThumbnailURL.Contains("ImageNotAvailable")))
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C# ?? operator in Ruby?
Is there a Ruby operator that does the same thing as C#'s ?? operator?
The ?? operator returns the left-hand
operand if it is not null, or else it
returns the right operand.
from http://msdn.microsoft.com/en-us/library/ms173224.aspx
The name of the operator is the null-coalescing operator. The original blog post I linked to that covered the differences in null coalescing between languages has been taken down. A newer comparison between C# and Ruby null coalescing can be found here.
In short, you can use ||, as in:
a_or_b = (a || b)
If you don't mind coalescing false, you can use the || operator:
a = b || c
If false can be a valid value, you can do:
a = b.nil? ? c : b
Where b is checked for nil, and if it is, a is assigned the value of c, and if not, b.
Be aware that Ruby has specific features for the usual null coalescing to [] or 0 or 0.0.
Instead of
x = y || [] # or...
x = y || 0
...you can (because NilClass implements them) just do...
x = y.to_a # => [] or ..
x = y.to_i # or .to_f, => 0
This makes certain common design patterns like:
(x || []).each do |y|
...look a bit nicer:
x.to_a.each do |y|