C# switch case, for/foreach loops and enum

Often in the earlier years of my software development career (esp. after working solely on SQL code for a long stretch of time), I would forget the exact syntax of some commonly used C# logic routines.

I've long since memorized the exact syntax for all of these, but I'd like to help someone else out there who may need a reminder in the future.

So here is a one-stop handy reference for these 3 commonly used C# constructs:

using System;
// enum
public enum Color { Red, Green, Blue }

public class Example
{   // switch
   public static void Main()
   {
      Color c = (Color) (new Random()).Next(0, 3);
      switch (c)
      {
         case Color.Red:
            Console.WriteLine("The color is red");
            break;
         case Color.Green:
            Console.WriteLine("The color is green");
            break;
         case Color.Blue:
            Console.WriteLine("The color is blue");   
            break;
         default:
            Console.WriteLine("The color is unknown.");
            break;   
      }
   }
}

// for loop
for (int i = 1; i <= 5; i++)
{
 Console.WriteLine(i);
}

 // foreach loop
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
    System.Console.WriteLine(element);
}

No comments: