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.
Related
I have this code:
if (App.selectedPhrases != null && App.selectedPhrases.Count != 0)
Is there a way I can simplify that using the ? operator to check for null rather than have two different checks with an && joining them?
You can use the null conditional member access operator (?.) to conditionally access a member only if it is not null, like so
if (App.selectedPhrases?.Count > 0)
I decided to use > instead of != as the Count of a collection cannot be smaller than 0, and null != 0 is true, which is incorrect in our case
I'd go with this:
// So if it's null, then return 0 so that the second check will not be true
if ((App.selectedPhrases?.Count ?? 0) != 0) {
// Do stuff
}
Try this:
if (App.selectedPhrases?.Count > 0)
Or:
if (!(new List<int?>{null, 0}.Contains(App.selectedPhrases?.Count)))
return ship.DefenseType?.PropulsionMethod != null
? new BattleMethod(ship.DefenseType.PropulsionMethod)
: null;
Hi, my current return statement, above, is returning a Propulsion method if it's not null. However, my database has different types of
propulsion methods denoted by the first 2 letters in the field(PK, PA, PT, etc).
How can I check to make sure that the PropulsionMethod starts with "PK" before going further into the return statement?
In pseudo code, it might look something like this:
if (ship.DefenseType?.PropulsionMethod).startsWith("PK")
&& ship.DefenseType?.PropulsionMethod != null)
{
return new BattleMethod(ship.DefenseType.PropulsionMethod)
}
else
{
return null;
}
I tried
return ship.DefenseType?.PropulsionMethod != null &&
ship.DefenseType?.PropulsionMethod.StartsWith("PK")
? new BattleMethod(ship.DefenseType.PropulsionMethod)
: null;
But I get this error:
operator && cannot be applied to operands of type bool and bool?
Just add this condition too:
return ship.DefenseType?.PropulsionMethod != null
&& ship.DefenseType?.PropulsionMethod.StartsWith("PK")
? new BattleMethod(ship.DefenseType.PropulsionMethod) : null;
As the operator is && so the second condition will be evaluated if the first one was true (not null in this case).
You can compare nullable bool directly with true:
return ship.DefenseType?.PropulsionMethod?.StartsWith("PK") == true
? new BattleMethod(ship.DefenseType.PropulsionMethod)
: null;
I am working on c# data model class, I created instance and assigning values from another object. I am aware of single line comparision but I need multiple, I have tried && operator but compiler complain 'invalid opperator'. I am sure what I am missing, surly it must be simple!
var answerDataModel = new AnswerDataModel()
{
Id = answerId,
//need help to
Value = AnswerDtoObject.Answers.FirstOrDefault() == null? &&
isSubQuestionExist == true ? "_SBQA"
: AnswerDtoObject.Answers.FirstOrDefault(),
};
if I remove "&& isSubQuestionExist == true ?", then code works
You have an errant ? operator. Just combine your comparisons in a single conditional operator:
Value = (AnswerDtoObject.Answers.FirstOrDefault() == null && isSubQuestionExist == true) ?
"_SBQA" :
AnswerDtoObject.Answers.FirstOrDefault()
Value = (AnswerDtoObject.Answers.FirstOrDefault() == null) &&
(isSubQuestionExist == true) ? "_SBQA"
: AnswerDtoObject.Answers.FirstOrDefault(),
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.
I have the below linq query which takes a text field which may be Y, N or DBnull and populates a boolean? parameter with either True, False or null depending on the value of the field.
var dset = from i in tbdc.Talkbacks
where i.talkback_id == id
select new Talkback(
i.talkback_id, i.acad_period, i.reference,
i.staff_member, i.date_received, i.no_talkers,
i.gender_id, i.names, i.type_id,
i.method_id, i.area_id, i.site_id,
i.category_id, i.date_closed, i.expenddate,
i.acknowledgementtarget,
(i.targetmet == "Y") ? true :
((i.targetmet == "N") ? false : null),
(i.acknowledgementtargetmet != "N") ? true : false
The problematic line is
(i.targetmet == "Y") ? true : ((i.targetmet == "N") ? false : null)
After reading up I found some documentation which states that the 2nd and 3rd arguments of the inline if need to be of the same type or be implicitly convertible to one another.
My question is, how do I get around this limitation to achieve my desired result?
I am relatively new to C# so am not familiar with all its quirks/capabilities yet.
My suggestion would be to replace it with :
(i.targetmet != null) ? (bool?)(i.targetmet == "Y") : null;
the reason why the compiler does not agree without the cast is that even if you store it into a nullable structure, the ternary operation checks if the results are compatible through an implicit conversion.
Results true and false are treated as bool literals, not bool?, thus not implicitly convertible to null. Casting either results to bool? will make them comparable. The one I suggested has an implicit convertion between bool? and null, and this works too:
(i.targetmet != null) ? (i.targetmet == "Y") : (bool?)null;
Which is an implicit conversion between a bool and bool?. I arbitrary prefer the first one..
You can explicitly convert one or more of the expressions to a bool?:
(i.targetmet == "Y") ? true : ((i.targetmet == "N") ? (bool?)false : (bool?)null)