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

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.

Related

Null Conditional Operator should used until what? ?.ToString()?.Trim() etc [duplicate]

This question already has answers here:
Why can I omit the subsequent null-conditional operators in an invocation chain?
(2 answers)
Closed 3 years ago.
I have misunderstanding some of Null-conditional operator ?. mechanism
Example getting Length of String variable
object variable = null;
int? Length = variable?.ToString()?.Trim()?.Length;
Should we using ?. operator in all cascading properties of members of object we need test ?
The variable object is null so testing with null-conditional operator should be for ToString() method only or cascading members of ToString() ?
This
?.ToString()?.Trim()?.Length
OR
?.ToString().Trim().Length
I though that if ToString is null there's no need for test next member after it.
The null-conditional operator is just syntactic sugar for a null-check. So the following two codes are similar:
object variable = null;
int? Length = variable?.ToString()?.Trim()?.Length;
VS:
object variable = null;
int? Length;
if(variable != null)
{
var a = variable.ToString()?;
if(a != null)
{
var result = a.Trim();
if(result != null)
Length = result.Length;
}
}
So depending on if the member can even return null- e.g. ToStringmay while Trim does not - you may have to check for it using ?.
In your example you can omit the check for Trim, but not for ToString.
Well, null conditional operator returns either null or some class; since int is a struct you can't put
// Doesn't compile. What is Length when variable == null?
int Length = variable?.ToString()?.Trim()?.Length;
but either use Nullable<int>
// Now Length can be null if variable is null
int? Length = variable?.ToString()?.Trim()?.Length;
or turn null into reasonable int:
// in case variable is null let Length be -1
int Length = variable?.ToString()?.Trim()?.Length ?? -1;
Since null.ToString() throws exception then ?. in variable?.ToString() is mandatory; all the other ?. are optional if we assume that ToString() and Trim() never return null.
if variable is null then ?. will immediately returns null
if variable is not null, both .ToString() and .Trim() will not return null and the check ?. is redundant.
So you can put either
int? Length = variable?.ToString().Trim().Length;
Or
int Length = variable?.ToString().Trim().Length ?? -1;

Linq ?? operator means [duplicate]

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.

A neater way of handling bools in C# [duplicate]

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;
}

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|

? Operator VS ?? Operator Usage

The following statement works:
Class.ID = odrDataReader["ID"] == null ? 0 : Convert.ToInt32(odrDataReader["ID"]);
But the following does not:
Class.ID = odrDataReader["ID"] as int? ?? 0; //ID is always 0
Any one can explain why ?? operator always returns 0 even when ID column is not null?
Solution(suggested by Kirk):
Class.ID = Convert.ToInt32(odrDataReader["ID"] ?? 0);
In first one you use Convert.ToInt32(odrDataReader["ID"]) in second one you use odrDataReader["ID"] as int?.
From what you say first one is correct, so you should use Convert in second too.
Actualy I think first is fine, because it would look weird if you really wanted to use ?? operator.
Edit:
To explain a bit odrDataReader["ID"] as int? is NOT a conversion. It will always return null if odrDataReader["ID"] is string.
It all depends on the type of the ID column. If it was indeed of type int?, then you should be able to do this with no problems:
Class.ID = (int?)odrDataReader["ID"] ?? 0;
However it is more likely that this is not the case and is a different type (I'd guess string). A string is clearly not a int? and thus odrDataReader["ID"] as int? always returns null and you get the value 0. As Euphoric mentions, the as operator only does reference/boxing conversions. If this is the case, using ?? is not an option for you and you must use the first expression.
It's definitely because you are doing odrDataReader["ID"] as int? - that is the difference between the two statements, and using the as keyword is not the same as doing a Convert.
If you want to use ?? you could try
Class.ID = Convert.ToInt32(odrDataReader["ID"] ?? 0);
Coalescing operator is new operator added in C#2.0. Coalescing operator is also known as ??.
Nullable<int> a = null;
Nullable<int> b = 10;
int c = a ?? b.Value;
Coalescing operator
Coalescing operator work some what similar to ternary operator but it works only with the Nullable types only. so its sort hand operator to deal with Nullable types only.
check my blog post : Coalescing operator - ??
the ?? operator is the null-coalescing operator. It defines a default value if the value is found to be null. Int32 is a value type in .NET, which normally can't take a null value, so the int? designates an Int32 that can be null.
Misread the question. I'm guessing it's because you're casting odrDataReader["ID"] to int? before checking it. You should try skipping the cast, though I doubt that's what's really the problem.

Categories

Resources