RobVious
RobVious

Reputation: 12915

How to simplify this C# if/else syntax

I have the following statement:

serverCard.Details = !String.IsNullOrEmpty(card.Details) ? card.Details : serverCard.Details;

I want to check and see if card.Details is null or empty... if not, write the value. Is there any syntax that allows me to leave out the else conditional?

Upvotes: 7

Views: 483

Answers (3)

mstrewe
mstrewe

Reputation: 416

You can write an extension method for String to check if nullOrEmpty. The regular if then would be shorter

Extension Method:

 public static bool IsNullOrEmpty(this string str)
 {
     return string.IsNullOrEmpty(str);
 }

 public static bool IsNullOrWhiteSpace(this string str)
 {
    return string.IsNullOrWhiteSpace(str);
 }

The if:

if(!card.Details.IsNullOrWhiteSpace())
    serverCard.Details = card.Details

The extension method will work for every string.

Upvotes: 0

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6039

You can always use the old if statement:

if(!String.IsNullOrEmpty(card.Details))
{
  serverCard.Details = card.Details;
}

I think the ternary operator is not needed here.

Upvotes: 5

Servy
Servy

Reputation: 203802

Sure, just use a regular if:

if(!String.IsNullOrEmpty(card.Details))
    serverCard.Details = card.Details

Upvotes: 16

Related Questions