repl.it
@kironroy/

fizzbuzz2

C#

with generics

fork
loading
Files
  • main.cs
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // string[] testArray;
            // multiple types can be held in an array

            // boxing and unboxing is expenisve when there are differnet types
            // List array allows developers to strongly type something and 
            // use same def for different types
            // examples below

            List<string> stringList = new List<string>();
            List<int> intList = new List<int>();

            stringList.Add("hi");
            intList.Add(1);

            //Console.WriteLine(FizzBuzz("123456789123456")); "FizzBuzz"

            string result = FizzBuzz("tests");

            Console.WriteLine($"Tests: {result}");

            result = FizzBuzz(123);

            Console.WriteLine($"Tests: {result}");

            result = FizzBuzz(true);

            Console.WriteLine($"True: {result}");

            result = FizzBuzz(new PersonModel { FirstName = "Tim", LastName = "Corey" });

            Console.WriteLine($"PersonModel: {result}");



            // ------------------------- Create your own generics -----------------------------

            Console.ReadLine();

        }

         // 3 = Fizz, 5 = Buzz, 3 & 5 = FizzBuzz
         // method below is private can't access outside the class
         // static, don't have to init to use FizzBuzz method

         // <T> something generic is here and (T item) means just one type
         // T is a convention letter (default)
        private static string FizzBuzz<T>(T item)
        {
            int itemLength = item.ToString().Length;
            string output = "";

            if (itemLength % 3 == 0)
            {
                output += "Fizz";
            }

            if (itemLength % 5 == 0)
            {
                output += "Buzz";
            }

            return output;
        }
      
    }

    public class PersonModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}