C
C#2y ago
Rhythmic

❔ Assigning variables in switch case

Why am I getting this error? I want to assign the value of totalBeat depending on the sign of measure. But the program thinks totalBeat is unassigned.
5 Replies
sibber
sibber2y ago
the switch doesnt cover all cases the compiler doesnt know that Math.Sign will only return 1 or -1
Pobiega
Pobiega2y ago
if you had a default case where you assigned it, or give it a default value when you declare it, it'd work also, in this case, consider using a switch expression instead of a switch statement will be much cleaner.
int totalBeat = Math.Sign(measure) switch
{
1 => measure * BeatsInMeasure + beat - 1,
-1 => (measure+1) * BeatsInMeasure - (BeatsInMeasure % beat)
};
int totalBeat = Math.Sign(measure) switch
{
1 => measure * BeatsInMeasure + beat - 1,
-1 => (measure+1) * BeatsInMeasure - (BeatsInMeasure % beat)
};
Rhythmic
RhythmicOP2y ago
I use a default value now, which fixes the error, but... Do you know why I get this warning? It looks like it thinks Math.Sign() might output 2
Hugh
Hugh2y ago
All the compiler knows is that Math.Sign() returns an int - even though we know that it can only return -1, 0, or 1, the compiler doesn't know that it can't return 512
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server