I'm currently using the following for counting forwards and backwards through an array depending on the current index.

If the index increments past the end of the array it now decrements and vice versa.

isReversed = isReversed ? index - 1 != -1 : index + 1 == array.Length;                    
       index = isReversed ? --index: ++index;

Can this approach be improved upon or have I tackled it in a reasonable manner?

Recommended Answers

All 8 Replies

It might help to know what you are trying to accomplish, unless this is just an exercise in theory.

It looks like you have assignment and comparison in the wrong places in the tertiary operator. Try rewriting that with an if-else.

It might help to know what you are trying to accomplish, unless this is just an exercise in theory.

Counter increments until it hits max limit, it then decrements.
Counter decrements until it hits min limit, it then increments.

I was wondering just how efficient my method is from an exercise point of view.

It looks like you have assignment and comparison in the wrong places in the tertiary operator

This method functions fine but I wasn't too sure about efficiency.

Write two versions of it the one you already have, and a newone with if statements.
Use the ildasm tool to watch how many il-instructions you gain or loose, so you can see for yourself what is best!
Success!

Write two versions of it the one you already have, and a newone with if statements.
Use the ildasm tool to watch how many il-instructions you gain or loose, so you can see for yourself what is best!
Success!

You can do this from within Visual Studio if you are debugging your application. Just right click and select Show Assembly.

Also, instead of setting a boolean to what direction, i'd set a value to add to the index (1 or -1) in the first conditional, then just adjust the value in the second statement (skipping the logic test).

commented: Excellent stuff, thank you :) +1

Also, instead of setting a boolean to what direction, i'd set a value to add to the index (1 or -1) in the first conditional, then just adjust the value in the second statement

Momerath could you please post an example of what you mean?

I still need the two tertiary operators as I need to determine which limit has been hit, min or max and which direction the counter is counting.

I've tried your way but I can't get it to work, embarrassingly so for me.

I've looked at this and can't come up with a less than 2 logic test, so you are good there :)

But, i'd change this line isReversed = isReversed ? index - 1 != -1 : index + 1 == array.Length; to isReversed = isReversed ? index != 0 : index + 1 == array.Length; and save two math operations.

Excellent, thank you. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.