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?
According to the error message the ternary operator cannot be used as a statement. You would need to do something like this to turn it into an assignment:
That being said, I’d recommend to just use if-then-else. It’s less confusing because it doesn’t involve the creation of “magic” dummy variables…