-3

I would like to refactor the following 2 lines of code:

var myDbObject = service.GetObj(id);
name = myDbObject != null ? myDbObject.Name : "No name";

How can I avoid using the auxiliar variable "myDbObject"?

Can I do this with only one line of code?

Is there any way of LINQ or something else to acomplish this?

Solutions that I am not looking:

  • using a service that returns the Name and not the full object;
  • calling the service more than one time.
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Dryadwoods
  • 2,875
  • 5
  • 42
  • 72
  • The null ternary (`??`)? – Cole Tobin May 23 '13 at 06:46
  • @ColeJohnson null ternary will assign myDbObject. Dry needs to assign it to myDbObject.Name – cheedep May 23 '13 at 06:49
  • @ColeJohnson are you telling me to use service.GetObj(id).Name ?? "No name" >> that will not work everytime the object is null I will have an exception when I access the property Name of a null. – Dryadwoods May 23 '13 at 06:50
  • @Dryadwoods what are you trying to achieve by not using the variable. Your option is using a try catch but Don't please. – cheedep May 23 '13 at 06:51
  • possible duplicate of [Deep Null checking, is there a better way?](http://stackoverflow.com/questions/2080647/deep-null-checking-is-there-a-better-way) – GSerg Jul 19 '14 at 06:57

1 Answers1

5
var name= service.GetObj(id)==null? "No name": service.GetObj(id).Name;
David
  • 15,894
  • 22
  • 55
  • 66
  • No, that is not a solution since you are calling the service 2 times and I do not want to do that. – Dryadwoods May 23 '13 at 06:48
  • 5
    @Dryadwoods - well that's a new constraint that you just introduced that wasn't mentioned in the question, so I'm going to +1 this answer. It's usually best to be clear on all constraints that you want to apply. – Damien_The_Unbeliever May 23 '13 at 06:52
  • @Dryadwoods, possibly impossible. Shall wait other's response. – David May 23 '13 at 06:53