-2

Is it possible to create the FizzBuzz solution in C# with the switch construct. I've found solutions that work for JavaScript and other languages, but these (or the syntax equivalent) don't seem to be working in C#.

For reference, I'll write the if statement version down below:

for (int x = 1; x <= 15; x++)
        {
            if (x % 5 == 0 && x % 3 == 0)
                Console.WriteLine("FizzBuzz");
            else if (x % 5 == 0)
                Console.WriteLine("Buzz");
            else if (x % 3 == 0)
                Console.WriteLine("Fizz");
            else
                Console.WriteLine(x);
        }
        Console.ReadLine();

EDIT: forgot to put my switch statement code, sorry about that:

for (x = 1; x <= 15; x++)
{
    switch (x)
    {
        case (x % 3 == 0 && x % 5 == 0):
            Console.WriteLine("FizzBuzz");
            break;
        case (x % 5 == 0):
            Console.WriteLine("Buzz");
            break;
        case (x % 3 == 0):
            Console.WriteLine("Fizz");
            break;
        default:
            Console.WriteLine(x);
            break;
    }
}

My problem is with the modulo statements. Error is "Cannot implicitly convert type bool to int. I've tried replacing switch (x) with switch (true) but that doesn't help much, just changes the error to "A constant value is expected" for each of my cases.

Macimoar
  • 69
  • 2
  • 8
  • 1
    if it works with an `if` it works with a `switch`, show us the code for the switch you've tried. – WilomGfx Sep 06 '18 at 17:20
  • 1
    Tons of examples of this online since this is a universal programming puzzle. – Parrish Husband Sep 06 '18 at 17:21
  • 2
    Hint: start with `switch(x%15)`. Now there are only maximum 15 cases. Which are they? – Eric Lippert Sep 06 '18 at 17:21
  • Saying "this doesn't seem to be working" and then **not showing the code that does not work** does not help us help you. You wrote some wrong code and then did not tell anyone what you wrote; we can't tell you how to fix it. – Eric Lippert Sep 06 '18 at 17:22
  • 3
    @WilomGfx That statement is not true in the general case. There is logic you can do with a `if` that you cannot with a `switch`, even with the new pattern matching. – juharr Sep 06 '18 at 17:30
  • @juharr Agreed, but for this problem, they are sure interchangeable. – WilomGfx Sep 06 '18 at 17:31
  • 1
    The argument to `switch` and the argument to `case` must resolve to the same type. You are "switching" on an `int` and then casing a `bool` – Rufus L Sep 06 '18 at 17:34
  • 1
    Your first `if` condition can be simplified to: `if (x % 15 == 0)` – Rufus L Sep 06 '18 at 18:05

4 Answers4

3

Like some of the others, I would go with a switch expression over a switch statement. However, I find using a tuple pattern cleaner:

static string FizzBuzz(int i)
{
     return (i % 3, i % 5) switch
     {
         (0, 0) => "FizzBuzz",
         (0, _) => "Fizz",
         (_, 0) => "Buzz",
         (_, _) => i.ToString()
     };
 }
1

This solution uses the switch expression as it is implemented in C# 8.0. Allows for quite concise code. It also uses the local static methods (also available since version 8.0):

public static void FizzBuzz(int n)
{
    for (var i = 0; i <= n; ++i)
    {
        var res = i switch
        {
            var x when is5(x) && is3(x) => "FizzBuzz",
            var x when is5(x) => "Fizz",
            var x when is3(x) => "Buzz",
            _ => i.ToString()
        };

        Console.WriteLine(res);
    }

    static bool is3(int x)
    {
        return x % 3 == 0;
    }
    static bool is5(int x)
    {
        return x % 5 == 0;
    }
}
PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
0

"Is it possible to create the FizzBuzz solution in C# with the switch construct"

Yes, it is possible, but not very practical (compared to an if statement). This is because you switch on an expression, and then your case statements must compare a constant expression to that value. So you can't do switch (0) and then case (i % 15) because i % 15 is not a constant expression.

Given this, you can switch on i % 15 to reduce the number of comparisons to the known base set, and then special-case the results that are divisible by 3, 5, and 15:

for (int x = 1; x <= 15; x++)
{
    switch (x % 15)
    {
        // Evenly divisible by 15
        case 0:
            Console.WriteLine("FizzBuzz");
            break;

        // Evenly divisible by 3
        case 3:
        case 6:
        case 9:
        case 12:
            Console.WriteLine("Fizz");
            break;

        // Evenly divisible by 5
        case 5:
        case 10:
            Console.WriteLine("Buzz");
            break;

        // Everything else
        default:
            Console.WriteLine(x);
            break;
    }
}

But the if statement is much more concise:

for (int x = 1; x <= 15; x++)
{
    if (x % 15 == 0) Console.WriteLine("FizzBuzz");
    else if (x % 3 == 0) Console.WriteLine("Fizz");
    else if (x % 5 == 0) Console.WriteLine("Buzz");
    else Console.WriteLine(x);
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • So, if I understand correctly, if I wanted to modify the for loop to go to 100 instead of 15, I would have to add 3,6,9,12,18,21,24... and so on for the cases divisible by 3 and he same with 5 and 15 manually? – Macimoar Sep 06 '18 at 20:12
  • No, did you try it? The `switch (x % 15)` reduces the number to the remainder of the number divided by `15`. So this will work with as many iterations as you like. – Rufus L Sep 06 '18 at 20:14
  • Oh yeah, you’re right. Sorry, I’m at work so I actually haven’t gotten the chance to sit down and try it. I just read the code wrong somehow, now I see what you mean. Thank you! – Macimoar Sep 06 '18 at 21:01
  • No problem, glad it helps! – Rufus L Sep 06 '18 at 21:01
0

It is possible to write a fizzbuzz as a simple switch.

It is just about as fast as an if else. I got a bit obsessed about this and created a little benchmark which I uploaded to git: https://github.com/chrisaddams/fizzbuzz-everyway-c-sharp

The results I found for speed are as follows:

Average Speed of Switch  is             63.46 ms
Average Speed of IfElseCont is          62.03 ms
Average Speed of If Else is             60.62 ms
Average Speed of If Only is             73.35 ms
Average Speed of If Cont is             73.55 ms

Anyway, here's the code, I think it's quite a neat and readable solution.

using System.Diagnostics;
using System;
namespace fizzbuzz
{
    class fizzyCase
    {
        static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            for (int i = 0; i <= 10000; i++)
            {
                switch (true)
                {
                    case var FizzBuzz when (i % 15 == 0):
                        Console.WriteLine("fizzbuzz");
                        break;
                    case var Fizz when (i % 3 == 0):
                        Console.WriteLine("fizz");
                        break;
                    case var Buzz when (i % 5 == 0):
                        Console.WriteLine("buzz");
                        break;
                    default:
                        Console.WriteLine(i);
                        break;
                }
            }
            timer.Stop();
            Console.WriteLine("Elapsed:{0}milliseconds", timer.Elapsed.TotalMilliseconds);

        }
    }
}
ChrisAddams
  • 190
  • 1
  • 8