webdad3
webdad3

Reputation: 9080

ternary statement Null or Blank

Currently I have the following ternary operation:

string value = "";

value = Company == null ? Name : Name + "," + Company;

Everything works great. However, I'd like to check if Company is null or "".

Is there a way to do that using a ternary statement?

Upvotes: 4

Views: 5470

Answers (4)

crthompson
crthompson

Reputation: 15875

Using IsNullOrEmpty

value = string.IsNullOrEmpty(Company) ? Name : Name + "," + Company;

There is a great debate on whether or not to use IsNullOrEmpty vs IsNullOrWhitespace on SO: string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

My favorite comment is:

For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.

See the reference here

Upvotes: 3

AwokeKnowing
AwokeKnowing

Reputation: 8246

if you don't want to use a string function just do

value= (Company==null || Company=="")?Name:Name + "," + Company;

it could be slightly faster. And if you know whether Company is more likely to be null or "", put the most likely one first, and it will be even faster because the second one won't be evaluated.

Upvotes: 1

Kamil Budziewski
Kamil Budziewski

Reputation: 23107

Use this String.IsNullOrWhiteSpace

value = string.IsNullOrWhiteSpace(Company) ? Name : Name + "," + Company;

of course you can also use this:

value = (Company == null || Company == "") ? Name : Name + "," + Company;

it's just for clarification that you can use more comples statements

Upvotes: 10

Habib
Habib

Reputation: 223312

use string.IsNullOrEmpty to check for null and empty string.

value = string.IsNullOrEmpty(Company) ? Name : Name + "," + Company;

if you are using .Net framework 4.0 or higher, and you want to consider white space as empty string as well then you can use string.IsNullOrWhiteSpace

Upvotes: 11

Related Questions