Reputation: 9080
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
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
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
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
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