3

In here i want to, If AvailCode comes as a null or empty string then i need to show it "Temporary Unavailable".But my coding doen't show that one. (Consider only Avail Code).

var _staff = trv.GetBookDetails("4500").Select(b => new
{
    value = b.bookno,
    text =  b.bookname + " " + "/"+" " + b.AvailCode ?? "TemporaryUnavailable",  
});
2
  • 1
    text = String.Format("{0} / {1}", b.bookname, String.IsNullOrEmpty(b.AvailCode) ? "TemporaryUnavailable" : b.AvailCode); Commented Feb 2, 2016 at 7:01
  • Above comment code also work. Commented Feb 2, 2016 at 7:07

3 Answers 3

6

the ?? operator only handles the NULL case, not the empty case

replace

b.AvailCode ?? "TemporaryUnavailable"

with

string.IsNullOrEmpty(b.AvailCode)? "TemporaryUnavailable" : b.AvailCode

so the correct line would be

text = b.bookname + " / " + (string.IsNullOrEmpty(b.AvailCode) ? "TemporaryUnavailable" : b.AvailCode),
Sign up to request clarification or add additional context in comments.

1 Comment

It shows me the error "Cannot implycitly convert type bool to string"
2

?? operator which called null-coalescing operator returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

This won't check for empty;

Use string.IsNullOrWhitespace method instead.

string.IsNullOrWhitespace(b.AvailCode) ? "TemporaryUnavailable" : b.AvailCode

Comments

1

Operator ?? has very low precedence, it's evaluated after the + operators on the left side. Therefore you can never really get null on the left side. You need to wrap into parenthesis:

  text =  b.bookname + " " + "/"+" " + (b.AvailCode ?? "TemporaryUnavailable"),  

or, in case you want to handle also empty:

  text =  b.bookname + " " + "/"+" " + (string.IsNullOrEmpty(b.AvailCode) ? "TemporaryUnavailable" : b.AvailCode),  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.