0

I want to call constructor of the class only if my object is not null. I can do it with "if else" but I have a lot of assignment like that and want to make it short. How can I write operator like null assignment "??" but it will work reverse.

From

LastMessage = item.LastMessage != null ? new MessageViewModel(item.LastMessage) : null;

To

LastMessage = item.LastMessage !? new MessageViewModel(item.LastMessage);

or (I am not sure this one gonna work but seems nice to me :) )

LastMessage = ? new MessageViewModel(item.LastMessage);
Tolga
  • 346
  • 2
  • 9
  • The first one is correct. What is the problem here? Are you asking how to create a new operator in c#? – Rufus L May 31 '19 at 21:11
  • 1
    https://stackoverflow.com/questions/1040114/is-it-possible-to-create-a-new-operator-in-c – adrianbanks May 31 '19 at 21:14
  • @RufusL actually yes, but I think it's not possible. Then I am looking for a smart solution instead of writing every time if else. Also, I have to check `if(item==null)return;` inside of the constructor all my viewmodels. Constructors can not return any value. If I don't check items.LastMessage for if null, it will create a new object(with all properties null or default) and assign it to back to LastMessage for nothing. Also, I don't have the chance if lastmessage is actually null. Sounds like something wrong with my implementation. – Tolga Jun 01 '19 at 14:38

0 Answers0