Search code examples
c#switch-statementinventory

Switch case items in an array to 'create' a cycle | c#


I want to be able to switch between an "active" object in an array by its index. In order to do this I need to be able to "cycle" through an array of objects with a fixed length of 3.

When active object the first item and the function switchObject() is called, I want to be able to change the active object to the second item in the array. Is this possible?

Inventory inventory = new Inventory(); /* has getObject() */
internal Object activeObject;

public void switchObject()
    {
        switch (index)
        {
            /* If active object index is 0, switch active object index to index 1 */
            case 0:
                index = 1;
                activeObject = inventory.getObject(index);

            /* If active object index is 1, switch active object index to index 2 */
            case 1:
                index = 2;
                activeObject = inventory.getObject(index);

            /* If active object index is 2, switch active object index to index 0 */
            case 2:
                index = 0;
                activeObject = inventory.getObject(index);

        }
    }

Desirable behaviour would be cyclical array, e.g. (where -> is switch())item 1 -> item 2 -> item 3 -> item 1 -> item 2 -> item 3 -> item 1 ....

This code throws errors in VS2017 as "Control cannot fall through from one case label('case ;')

Also, is there a way I can utilise exceptions (possibly a custom exception?) to check if there are actually three objects available to switch between?

Thanks!

Is there a way I could get this working?


Solution

  • You are missing break; statement at the end of each case. And you can add a default case which you can use to throw exception if the index is not between 1-3.

    switch (index)
        {
            /* If active object index is 0, switch active object index to index 1 */
            case 0:
                index = 1;
                activeObject = inventory.getObject(index);
                break;
    
            /* If active object index is 1, switch active object index to index 2 */
            case 1:
                index = 2;
                activeObject = inventory.getObject(index);
                break;
    
            /* If active object index is 2, switch active object index to index 0 */
            case 2:
                index = 0;
                activeObject = inventory.getObject(index);
                break;
            default:
                throw new Exception("Index can only be 1, 2 or 3");
        }
    

    Note: the default section does not need break statement, because the exception thrown breaks to switch flow.

    Hope this helps!