Hi I have some code here which I dont understand
public ObservableCollection<Packet> Items
{
get
{
this.items = this.items ?? this.LoadItems();
return this.items;
}
}
What does the ?? means?
?? is the null-coalescing operator. The value on the left is returned as long as it is not null. If it is null, then the value on the right is returned.
a = b ?? c;
Is equivalent to:
if (b != null)
a = b;
else
a = c;
That is the null coalescing operator.
It says; assign items to items unless items is null, in which case, call LoadItems and assign the result. It is shorthand for
if( this.items == null )
this.items = this.LoadItems();
return this.items;
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
Reference.
It's called the "null-coalescing operator", and is documented at http://msdn.microsoft.com/en-us/library/ms173224.aspx.
Related
Hello i am trying to use if statement when adding values to an array.
object[] array = new object[10]
{
defect.RecordStation,
defect.RecordUser,
repairTypeDict[defect.Id],
defect.Concern,
defect.Comments,
defect.RespCell,
null,
locationpartDict[defect.Id],
if( repairStandardTimeDict[defect.Id] == null)
repairActualTimeDict[defect.Id];
else
repairStandardTimeDict[defect.Id];
,
defect.Id,
};
i want to use the statement as 1 object
if( repairStandardTimeDict[defect.Id] == null)
repairActualTimeDict[defect.Id];
else
repairStandardTimeDict[defect.Id];
Thank you for help
The following expression
if( repairStandardTimeDict[defect.Id] == null)
repairActualTimeDict[defect.Id];
else
repairStandardTimeDict[defect.Id];
can be transformed to a single statement by using the ?: conditional operator
repairStandardTimeDict[defect.Id] == null
? repairActualTimeDict[defect.Id];
: repairStandardTimeDict[defect.Id];
or
repairStandardTimeDict[defect.Id] != null
? repairStandardTimeDict[defect.Id]
: repairActualTimeDict[defect.Id];;
The latter can be further simplified by ?? null-coalescing operator
repairStandardTimeDict[defect.Id] ?? repairActualTimeDict[defect.Id]
Here if the left hand side is not null then take that value otherwise take the right hand side.
You can use the null coleascing operator which would be object ?? valueIfObjectNull.
What this means is if the object on the left of the operator is null, it will default to the value on the right of the operator.
Is this possible in one line of code ? null : yourHelpfulAnswer
Thank you in advance.
var x = await Foo_Get() == null ? 123: Foo.SomeProperty;
Just seems like there is a much better way than:
var myVal = 123;
var foo = await Foo_Get();
if(foo != null) myVal = foo.SomeProperty;
That should do the trick:
var myVal = (await Foo_Get())?.SomeProperty ?? 123;
Simplified:
? = if value on left is null use null, otherwise use property
?? = if value on the left is null use the value on the right instead.
You can use the null coalescing operator to set myVal:
var myVal = (await Foo_Get())?.SomeProperty ?? 123;
Is it possible to simplify the below condition using the null-coalescing operator or any other simplified code?
int? c,a,b;
if(a!=null)
{
c = a;
}
else if(b!=null)
{
c = b;
}
else
{
c = null;
}
Thanks in Advance
You mean something like:
int? c = a ?? (b ?? null)
Note that according to your if-else statement, c has to be int? type. For the same reason, it makes sense both a and b are of int? type.
Hence, as b may be null, the same expression can be rewritten as:
int? c = a ?? b;
c = a ?? b ?? null;
Although if your catch is null anyways then you only really need
c = a ?? b;
Edit: As other users have stated it's important that your int is nullable (int?) if you're working with them.
Assuming that they are all of Type int?
int? c = a ?? b; //no need for an explicit null. If b is null so will c be.
because the question doesn't make sense if they are of Type int.
I'm creating some objects to return to a form via API, and the objects are derived from database values, including values that could be null in the database, but cannot be null in the context of my API (I am obtaining data from multiple tables, so I know that if a field is null in one table, I can obtain a legitimate value from another table):
List<ResultsByLineShiftSlot> returnResults = new List<ResultsByLineShiftSlot>();
foreach (LineShiftSlot ls in db.LineShiftSlots.OrderBy(ls => ls.ScheduledDateAndTime).Where(ls => ls.ProductionDate == slotDate &&
ls.ShiftId == shiftId &&
ls.LineId == lineId &&
ls.Quantity > 0 &&
ls.BlendId != null))
{
var recordedResult = db.LineShiftSlotResults.FirstOrDefault(r => r.LineShiftSlotId == ls.Id);
if (recordedResult != null)
{
ResultsByLineShiftSlot returnResult = new ResultsByLineShiftSlot
{
BlendId = recordedResult.BlendId
};
}
else
{
ResultsByLineShiftSlot returnResult = new ResultsByLineShiftSlot
{
BlendId = ls.BlendId ?? 0
};
}
}
return returnResults;
In the above example, BlendId can be null in LineShiftSlots, but not in LineShiftSlotResults.
In this context where a nullable variable is known to contain a non-null value, which is better?
Should I use the null coalescing operator:
BlendId = ls.BlendId ?? 0
Or should I use .Value():
BlendId = ls.BlendId.value()
Both compile, and seem to work.
Are they functionally equivalent in this context? Is using one over the other better practice? I know that .value() could potentially return an exception, whereas the null coalescing operator could not, but in this case .value can never be null.
In the general case, they're not semantically equivalent.
labelId = recordValue.labelId.Value;
This one means I know the value can't be null. Just throw if my assumption is wrong.
On the other hand,
labelId = recordValue.labelId ?? 0;
labelId = recordValue.labelId.GetValueOrDefault();
These two mean that the value may be null, and if that happens, just ignore it, considering it's normal, and substitute it with the default value.
I'd use GetValueOrDefault() in that case, it makes it somewhat more obvious (and the JIT will inline this method).
However, your code is equivalent to this simpler alternative:
labelId = recordValue.labelId ?? otherValue;
In this case the code would be the same however have you considered the following
labelId = recordValue.labelId ?? otherValue
which is essentially the following
if(recordValue.labelId != null){
labelId = recordValue.labelId.Value;
}
else
{
labelId = otherValue;
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What do two question marks together mean in C#?
Hi, I was looking for some trainings of MVC 2 in C# and I found this sintax:
ViewData["something"] = something ?? true;
So, what is that '??' means ?.
It's the null-coalescing operator.
It returns the first argument unless it is null, in which case it returns the second.
x ?? y is roughly equivalent to this (except that the first argument is only evaluated once):
if (x == null)
{
result = y;
}
else
{
result = x;
}
Or alternatively:
(x == null) ? y : x
It is useful for providing a default value for when a value can be null:
Color color = user.FavouriteColor ?? defaultColor;
COALESCE
When used in a LINQ to SQL query the ?? operator can be translated to a call to COALESCE. For example this LINQ query:
var query = dataContext.Table1.Select(x => x.Col1 ?? "default");
can result in this SQL query:
SELECT COALESCE([t0].[col1],#p0) AS [value]
FROM [dbo].[table1] AS [t0]
It is the null coalescing operator. The return value is the left hand side if it is non-null and the right hand side otherwise. It works for both reference types and nullables
var x = "foo" ?? "bar"; // "foo" wins
string y = null;
var z = y ?? "bar"; // "bar" wins
int? n = null;
var t = n ?? 5; // 5 wins
If something is null, it returns true, otherwise it returns something.
See this link for more.