2

I am sending value in object orderContract which will replace values of entity if contract value is not null but if contract property is null it will retain its own value.

Currently I have used coalesce operator as in 2nd line of code. Is there a way where I don't have to repeat existing value?

 var ordersEntity = _repository.Read<Entities.Orders>(orderContract.Id);

ordersEntity.Status = orderContract.Status ?? ordersEntity.Status;
TylerH
  • 20,799
  • 66
  • 75
  • 101
Manjay_TBAG
  • 2,176
  • 3
  • 23
  • 43
  • 1
    No, there is no `??=` or `?=` operator. – René Vogt Aug 26 '19 at 13:57
  • 1
    No. The only alternative is to use an `if` to only assign if its null, but you're still repeating the code. `if (orderContract.Status == null) { orderContract.Status = ordersEntity.Status; }` –  Aug 26 '19 at 13:59
  • You could change the property to be nullable, and change the property's setter to ignore nulls, but that seems silly to save yourself a few key presses (Ctrl-C, Ctrl-V on Windows)... Not to mention it would add code to those places where you get the value (to add `.GetValueOrDefault()` or `?.Value` or whatever). – Heretic Monkey Aug 26 '19 at 14:03
  • 2
    There actually [might be a `??=`](https://github.com/dotnet/csharplang/issues/2072) eventually (with different semantics than what you need here!), but even then I'd still prefer an explicit `if (orderContract.Status != null) ordersEntity.Status = orderContract.Status` over a redundant assignment, which might have side effects if you're unlucky. (The fact that a previous comment got the logic wrong is also an argument in favor of that, I think.) – Jeroen Mostert Aug 26 '19 at 14:04
  • If that something you repeat to much you can move it in the setter/getter – xdtTransform Aug 26 '19 at 14:04
  • @RenéVogt The `??=` is proposed for C# 8, but it would still not apply if you read carefully... Also @Amy: your assignment is not the same as OP's. – Peter B Aug 26 '19 at 14:06
  • @PeterB ah right, msiread that. – René Vogt Aug 26 '19 at 14:12
  • Thanks everyone. I will go with use of Coalesce rather than if statement. – Manjay_TBAG Aug 26 '19 at 14:18

0 Answers0