1

I just wrote a program with manny Cases and Switches. So in C# is there any way to avoid Cases and Switches? I ended up with kind of a "messy" program in my point of view. All the other senior full stack developer, they said it was good and so on.

But basically i'm just curious about your thoughts in this subject? Do you know any better way to do smart coding without Cases and Switches?

Basically it's in my nature to questioning things, the status quo....

Andy
  • 37
  • 1
  • 4
  • 2
    it depends on what you are coding, switch statements are a clean and efficient – BugFinder Dec 12 '16 at 09:16
  • 1
    Define "smart coding". Switch/case blocks are tools, just like everything else in the C# language specification. It has places that it is ideal for and other places that something else would be more suitable. I will say that you shouldn't be nesting them, though. – Abion47 Dec 12 '16 at 09:17
  • It depends. If there are a lot of cases and the cases may be added to in the future, some form of lookup table may be more suitable. – Justin Harvey Dec 12 '16 at 09:19
  • I agree with @BugFinder - you could replace any switch-case with an `if-elseif-else` - but this will make your code even harder to read. If your statment gets realy large - put it into a method, so at least it's kind of encapsulated. In switch-cases you nearly always can work with an enum, what at least makes it a bit more readable. – TripleEEE Dec 12 '16 at 09:19
  • This question is too broad and because of that, opinion based. You would get better results if you have a particularly "messy" switch you can show, including what you're using it for. It'd more like a code review though. – C.Evenhuis Dec 12 '16 at 09:29
  • Well, in times of "stupid" compilers was this type of coding real performance problem. Modern compilers will translate larger case-switch into hash table structure (CIL) so performance problem is gone. We can say that switch-case is in larger structures more efective then if-else if statement. I don't think that you can completely avoid them. There still are situations when you need to use switch/case (if/else if). That's why modern languages still support them. – MartinS Dec 12 '16 at 09:35
  • Well "messy" its like you end up with many Cases and Switches. So not realy messy but it takes up so manny lines of code. Yes i know if elif and so on but that was why Cases and Switches was implemented. To get away from those ones. Or maby im just thinking to much – Andy Dec 12 '16 at 09:39

2 Answers2

4

Each particular case requires its own personal decision. There are cases when hundreds lines of dummy-looked code achieve the goal much better that a beautifully couple- of-lines complex logic with recursions, referneces to 3rd-parties, LINQs and so on.

But talking about alternatives I can suggest dictionaries:

var switchCaseAlternative = new Dictionary<string, Action>() 
{
   {"case1", () => {System.Diagnostic.Debug.WriteLine("One");}},
   {"case2", () => {System.Diagnostic.Debug.WriteLine("Two");}}
};

then the use instruction will look like:

  switchCaseAlternative["case1"]();
Yaugen Vlasau
  • 2,148
  • 1
  • 17
  • 38
  • 1
    Perfect never seen that one, so now i will go home and read up about it. – Andy Dec 12 '16 at 09:50
  • That's a real cool thing - I Never saw this one either. I'll remember this! – TripleEEE Dec 12 '16 at 16:09
  • 1
    While this is an elegant alternative, I'm not sure I would ever recommend it. The only time I would see this as a more desirable option than switch/case is if the program is dynamically adding case statements at runtime. Otherwise, this is just as cumbersome (if not more so) for a larger memory footprint and worse performance. – Abion47 Dec 13 '16 at 04:31
2

You can try use inheritance of your classes. Switch means that you need to do somthing similar with different values. Hopes, that example below can help to understand my idea:

public enum SexTypes { Unknown, Male, Female }

public abstract class Human
{
    protected string HelloMessage = "common message part";
    public abstract SexTypes Sex { get; }

    public void SayHello() => Console.WriteLine(HelloMessage); //good way

    public void SayHelloWithSwitch() //bad way
    {
        switch(Sex)
        {
            case SexTypes.Unknown:
                Console.WriteLine(HelloMessage);
                break;
            case SexTypes.Male:
                Console.WriteLine(HelloMessage + " some modifications");
                break;
            case SexTypes.Female:
                Console.WriteLine("new other message");
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }
    }
}

public class Boy : Human
{
    public override SexTypes Sex => SexTypes.Male;
    protected new string HelloMessage => base.HelloMessage += " , some message modifications";
}

public class Girl : Human
{
    public override SexTypes Sex => SexTypes.Female;
    protected new string HelloMessage = "overwrite all message";
}
Fatality
  • 21
  • 1
  • 2