Not a statement?

Posted by abelenky on Stack Overflow See other posts from Stack Overflow or by abelenky
Published on 2010-04-06T16:10:54Z Indexed on 2010/04/06 16:13 UTC
Read the original article Hit count: 187

Filed under:

I have a simple little code fragment that is frustrating me:

HashSet<long> groupUIDs = new HashSet<long>();
groupUIDs.Add(uid)? unique++ : dupes++;

At compile time, it generates the error:

Only assignment, call, increment, decrement, and new object expressions can be used as a statement

HashSet.Add is documented to return a bool, so the ternary (?) operator should work, and this looks like a completely legitimate way to track the number of unique and duplicate items I add to a hash-set.

When I reformat it as a if-then-else, it works fine.

Can anyone explain the error, and if there is a way to do this as a simple ternary operator?

© Stack Overflow or respective owner

Related posts about c#