Ad

FizzBuzz using pattern matching

Code
Diff
  • using System;
    
    namespace Solution {
      class FizzBuzz {
        public static string Convert(int input) => input switch
        {
          {} when input.IsDivisibleBy(3) && input.IsDivisibleBy(5) => "FizzBuzz",
          {} when input.IsDivisibleBy(3) => "Fizz",
          {} when input.IsDivisibleBy(5) => "Buzz",
          _ => input.ToString()
        };
      }
      
      static class IntExtensions {
        public static bool IsDivisibleBy(this int dividend, int divisor) => dividend % divisor == 0;
      }
    }
    • using System;
    • namespace Solution {
    • class FizzBuzz {
    • public static string Convert(int input)
    • {
    • var divisableBy3 = input % 3 == 0;
    • var divisableBy5 = input % 5 == 0;
    • return (!divisableBy3 & !divisableBy5) ? input.ToString()
    • : (divisableBy3 ? "Fizz" : string.Empty) + (divisableBy5 ? "Buzz" : string.Empty);
    • }
    • public static string Convert(int input) => input switch
    • {
    • {} when input.IsDivisibleBy(3) && input.IsDivisibleBy(5) => "FizzBuzz",
    • {} when input.IsDivisibleBy(3) => "Fizz",
    • {} when input.IsDivisibleBy(5) => "Buzz",
    • _ => input.ToString()
    • };
    • }
    • static class IntExtensions {
    • public static bool IsDivisibleBy(this int dividend, int divisor) => dividend % divisor == 0;
    • }
    • }