4

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?

webdad3
  • 8,893
  • 30
  • 121
  • 223

4 Answers4

11

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

Habib
  • 219,104
  • 29
  • 407
  • 436
10

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

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
3

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

Community
  • 1
  • 1
crthompson
  • 15,653
  • 6
  • 58
  • 80
1

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.

AwokeKnowing
  • 7,728
  • 9
  • 36
  • 47