Linq ?? operator means [duplicate] - c#

This question already has an answer here:
C# coalesce operator
(1 answer)
Closed 4 years ago.
Good Day.
Sorry before i'm a beginner on linq. can i ask what is the meaning of ?? in linq
.Where(w => ((w.BalancedDate ?? w.OriginalDateByAMT) >= filter.start_date && (w.BalancedDate ?? w.OriginalDateByAMT) <= filter.end_date) || w.ReplaceByEHValidation == true)
Thanks

It's not a linq operator, but it means if the left hand property is null, then use the right hand property.

If the value on the left side of ?? is null, then it takes the value of the right side.
I.e.
var x = y ?? z;
If y is not null then x=y otherwise x=z

Yes, this question was already answered on the link shared on the comments. It is a Nullable type or null-coalescing, it returns the left value if not null or else it returns the right one.

Related

Does an if statement return immediately when one of the conditions is false [duplicate]

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

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
}

What is the most concise way to write the opposite of a null coalesce [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there an “opposite” to the null coalescing operator? (…in any language?)
Is there a more concise way of writing the third line here?
int? i = GetSomeNullableInt();
int? j = GetAnother();
int k = i == null ? i : j;
I know of the null coalescing operator but the behaviour I'm looking for is the opposite of this:
int k == i ?? j;
Sneaky - you edited it while I was replying. :)
I do not believe there is a more concise way of writing that. However, I would use the "HasValue" property, rather than == null. Easier to see your intent that way.
int? k = !i.HasValue ? i : j;
(BTW - k has to be nullable, too.)
In C#, the code you have is the most concise way to write what you want.
What is the point of that operator? The use cases are pretty limited. If you're looking for a single-line solution without having to use a temporary variable, it's not needed in the first place.
int k = GetSomeNullableInt() == null ? null : GetAnother();

Ruby's equivalent to C#'s ?? operator [duplicate]

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|

What does ?? mean in C#? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What do two question marks together mean in C#?
What does the ?? mean in this C# statement?
int availableUnits = unitsInStock ?? 0;
if (unitsInStock != null)
availableUnits = unitsInStock;
else
availableUnits = 0;
This is the null coalescing operator. It translates to: availableUnits equals unitsInStock unless unitsInStock equals null, in which case availableUnits equals 0.
It is used to change nullable types into value types.
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
?? Operator (C# Reference)
according to MSDN, The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
Check out
http://msdn.microsoft.com/en-us/library/ms173224.aspx
it means the availableUnits variable will be == unitsInStock unless unitsInStock == 0, in which case availableUnits is null.

Categories

Resources