[C#] Is this incrementation ternary method sensible?

Started by
80 comments, last by _the_phantom_ 14 years, 2 months ago
I've got the following for obtaining the next frame index for my animation:

// Use current frame
...

// Get the next frame
frame_Index = ++frame_Index > frame_Finish ? frame_Start : frame_Index;
Is it sensible to use ++frame_Index by incrementing the value for frame_Index so frame_Index is the correct value after the evaluation without needing to increment it again? Thanks.
Advertisement
While it might be syntactically correct, and it might even work reliably (honestly, I have no idea...), I would be less than pleased if I happened across that in code I had to work with.
Can you please elaborate and show me what you would consider a better choice?
frameIndex++;if(frameIndex > frameFinish){    frameIndex = frameStart;}
I would personally use:
if (frame_Index >= frame_Finish) {  frame_Index = frame_Start;} else {  ++frame_Index;}

Though I'd still find Telastyn's version acceptable.
Thanks guys.

I must confess, my love for ternary operators is probably going to get me into trouble!
I wouldn't mind a one-liner in this particular example, but I suspect I'm in the minority here.
Quote:Original post by Spa8nky
Thanks guys.

I must confess, my love for ternary operators is probably going to get me into trouble!

You're not alone, I cannot keep my fingers off them. Writing code as concisely as possible is fun (e.g. code golf...). However, I agree that one should abstain from using such contraptions in production code.
I don't mind the ternary operator in this case, just using it in the same line as you increment a variable you're already assigning to. Even if that's well-defined in C#, it's still a little confusing.
Or an even shorter version of Telastyn's code:
if (++frame_Index > frame_Finish)    frame_Index = frame_Start;

Personally that makes a lot more sense than any of the others; it says "if we increment the frame index and it turns out to be past the finish frame, then set it to the starting frame."

This topic is closed to new replies.

Advertisement