Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Case which include other cases

How to execute in one case, other cases? I could just copy paste those other cases, or put it to some external function but there is so much code so I dont want to do that.

Example:

 switch(foo) 
 {     
    case 3:     
    {             
        //something     
    }break;          
    
    case 4:     
    {             
        //something else     
    }break;      
    
    case 5:     
    {             
        //here i want to execute case 3 and case 4     
    }break;      
}

I think that this was previously answered but I can’t find how to do it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

C# doesn’t have such functionality. You have to create other methods which will do actions for cases 3 and 4 and call them from case 5 branch. I would suggest to create a separate class FooHandler which would handle your value. It’s easily extendable and readable.

public class FooHandler
{
    private readonly int _foo;

    public FooHandler(int foo)
    {
        this._foo = foo;
    }

    public void Handle()
    {
        switch(this._foo) 
        {     
            case 3: this.HandleCase3(); break;          
            case 4: this.HandleCase4(); break;
            case 5: this.HandleCase5(); break;
            default: throw new ArgumentException("Foo value is invalid");
        }
    }
    
    private void HandleCase3()
    {
        // Your code for case 3
    }

    private void HandleCase4()
    {
        // Your code for case 3
    }

    private void HandleCase5()
    {
        this.HandleCase3();
        this.HandleCase4();
    }
}

Usage:

var fooHandler = new FooHandler(foo);
fooHandler.Handle();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading