Reputation: 375
I tried the following:
(id == title) | (id.IsNullOrEmpty) ? "class='enabled'" : ""
But it gives a message saying "Error 22 Operator '|' cannot be applied to operands of type 'bool' and 'method group'
Can anyone tell me what's wrong. Both id and title are strings.
Upvotes: 3
Views: 1355
Reputation: 449
You're using bitwise OR (|). You need logical OR (||).
if ( id == null || id == title )
{
// id is null or id equals title.
}
Note that the equality operator (==) is case sensitive. To do a case insensitive comparison use the static method String.Compare.
if ( id == null || String.Compare( id, title, true ) == 0 )
{
// id is null or id equals title (ignoring case).
}
Upvotes: 0
Reputation: 46480
I'm not a C# developer, but try || instead of |. The difference between the operators is explained here http://msdn.microsoft.com/en-us/library/aa691310(v=vs.71).aspx.
Also, is ==
the correct way to compare strings in C#? In Java you need to use .equals()
.
(UPDATED: apparently | is nothing to do with the bitwise operator).
Upvotes: 5
Reputation: 48596
If you want to test for "Is this string null (or empty) or equal to another string", then just say that:
if (string.IsNullOrEmpty(id) || id.Equals(title))
{
// Code here
}
As a ternary operation:
var result = (string.IsNullOrEmpty(id) || id.Equals(title) ? "class='enabled'" : "";
Upvotes: 0
Reputation: 52788
Try it like this instead:
(id == title) || id.IsNullOrEmpty() ? "class='enabled'" : ""
Upvotes: 0
Reputation: 754545
Looks like you're using |
instead of ||
and I'm not sure if you have IsNullOrEmpty
defined as an extension method but you're mussing the ()
to invoke it. That or just call String.IsNullOrEmpty
directly.
Try the following
(id == title || String.IsNullOrEmpty(id)) ? "class='enabled'" : ""
Upvotes: 10