Lesson # 6. Enumerations and Sequences

Programming on c sharp in Microsoft Visual Studio. Using methods or functions.

Lesson # 6. Theory

Lecture in pdf format

  • An enumeration type, or enum, is a structure that enables you to create a variable with a fixed set of possible values. The most common example is to use an enum to define the day of the week. There are only seven possible values for days of the week, and you can be reasonably certain that these values will never change.
  • A best practice would be to define your enum directly within a namespace so that all classes in that namespace will have access to it, if needed. You can also nest your enums within classes or structs.
  • By default enum values start at 0 and each successive member is increased by a value of 1.
  • Creating and Using Enums

  • To create an enum, you declare it in your code file with the following syntax, which demonstrates creating an enum called Day, that contains the days of the week:
  • enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, 
       Saturday };
  • By default enum values start at 0 and each successive member is increased by a value of 1. As a result, the previous enum ‘Day’ would contain the values:
  • Sunday = 0
    Monday = 1
    Tuesday = 2
    etc.
  • You can change the default by specifying a starting value for your enum as in the following example:
  • enum Day { Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
  • In this example, Sunday is given the value 1 instead of the default of 0. Now Monday is 2, Tuesday is 3, etc.
  • The keyword enum is used to specify the «type» that the variable Day will be. In this case, an enumeration type.
  • Using an Enum

    // Set an enum variable by name.
    Day favoriteDay = Day.Friday;
    // Set an enum variable by value.
    Day favoriteDay = (Day)4;
  • The default enumeration types are int, but you can also use the byte, sbyte, short, ushort, int, uint, long, and ulong types.
  • Example of declaring an enumeration of type short
  • enum DayOfTheWeek_v3 : short
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }
  • To get the value of an enumerator, you must cast the enumerator type to the enumeration type
  • Console.WriteLine((int)DayOfTheWeek.Tuesday);
    

Sequences

To have sequences in your code two directives must be included:

using System.Collections.Generic;
using System.Linq;
Sequence generators

Example: Generates a sequence of integral numbers within a specified range:

Range (int start, int count);
  • start — The value of the first integer in the sequence.
  • count — The number of sequential integers to generate.
  •   

    IEnumerable<int> seq; // definition
    seq = System.Linq.Enumerable.Range(3, 10);
    foreach (var x in seq)
        Console.Write($"{x} "); // 3 4 5 6 7 8 9 10 11 12
    Sequence generators with lambda-expressions
    Where query:

    Example: Generates a sequence of integers from 1 to 10 and then select evens:

    IEnumerable<int> s;
    s = Enumerable.Range(1, 10); // 1 2 3 4 5 6 7 8 9 10
    s = s.Where(x => x % 2 == 0); //2 4 6 8 10
    foreach (int num in s)
      {
        Console.WriteLine(num);
      }
    Select query:

    Example: Generates a sequence of integers from 1 to 10 and then select their squares:

    IEnumerable<int> squares;
    squares=Enumerable.Range(1, 10).Select(x => x * x);
    foreach (int num in squares)
      {
        Console.WriteLine(num);
      }

    Example: Generates a sequence of integers from 1 to 9 with elements: (a+b)*2 (i.е. for first two elements we’ll have (0+1)*2 = 2)

    IEnumerable<int> seq;
    seq= Enumerable.Range(1, 9).Select((a, b) => (a+b)*2);
    foreach (int num in seq)
    			{
    				Console.Write(num); // 2 6 10 14 18 22 26 30 34
    			}

    Labs and tasks

    Lab 1. Enumarations

    To do: Request user to input a number — a mark (1, 2, 3, 4, 5). Check the inputted number to print out the description of the mark (very_bad — 1, bad — 2, satisfactory — 3, good — 4, excellent — 5). And also output the mark for the characteristic of satisfactory.

    Note: Create a function CheckMark with o switch statement in it to check the mark.

    [Solution and Project name: Lesson_6Lab1, file name L6Lab1.cs]

    Expected output:

    Please enter a number
    2 
    The characteristic for 2 is: bad
    And also the characteristic satisfactory is for: 3 mark 
    

    ✍ Algorithm:

    • Create Console Application with the name Lesson_6Lab1.
    • In the Solution Explorer window find a file Program.cs and rename it into L6Lab1.cs.
    • In order not to print always the class Console, we can include it right in the beginning of the editor window:
    • ...
      using static System.Console;
      ...
      
    • After the opening brace for the class Program and just before the Main() method, enter the following code to create an enum called Marks, that represents characteristics of the marks:
    • ...
      enum Marks { very_bad, bad, satisfactory, good, excellent, noSuchMark };
      ...
      
    • Inside Main() add the following code.
    • ...
      int x = (int)Marks.satisfactory;
      Console.WriteLine($"And also the characteristic satisfactory is for: {x} mark");
      ...
      
    • This code shows the use of enumerations in two aspects. First, you are using Intellisense when you type in Marks.satisfactory. Second, the internal representation of these enumeration values are numeric so you can convert them to int data types and display them as such.
    • Run the program by pressing CTRL+F5 to see the output.
    • Under this code request the user to input the number (15):
    • ...
      WriteLine("Please enter a number");
      int mark = int.Parse(ReadLine());
      ...
      
    • Create a function with the name CheckMark and two parameters: int parameter mark to accept the mark and ref parameter with a name characteristic of the type of the enum Marks.
    • static void CheckMark(int mark, ref Marks characteristic)
        {
        ...
        }
      
    • In the function create the switch statement to check an inputted number and to assign the characteristic result to the characteristic parameter:
    • switch (mark)
                  {
                        case 1:
                          characteristic = Marks.very_bad;
                          break;
                        case 2:
                          characteristic = Marks.bad;
                          break;
                        case 3:
                          characteristic = Marks.satisfactory;
                          break;
                        case 4:
                          characteristic = Marks.good;
                          break;
                        case 5:
                          characteristic = Marks.excellent;
                          break;
                      default:
                          WriteLine("Invalid selection. Please select 1, 2, 3, 4 or 5.");
                          characteristic = Marks.noSuchMark;
                          break;
                  }
      
    • In the main function initialize the variables to use them as the parameters for the function:
    • ...
              WriteLine("Please enter a number"); // it was already here
              int mark = int.Parse(ReadLine()); // it was already here
              Marks characteristic = Marks.very_bad; // it must be assigned some value, no matter which one
      
    • After, call the function and output the results:
    • ...
         CheckMark(mark, ref characteristic);
         WriteLine($"The characteristic for {mark} is: {characteristic}");
      
    • Run the program by pressing CTRL+F5 to see the output.

    🎦


    Task 1 for Lesson #6:

    To do: Create Console Application with the name Lesson_6Task1. Remove the main function from the project. Copy the code from the text-file, and insert this code to the main class (class Program) of the created project. Follow all the tags TODO and make the tasks written there. Make sure the project works properly.
      
    Expected output:

    Please enter the day of the week:
    2
    Tuesday
    
    Please enter the day of the week:
    9
    Необработанное исключение: System.ArgumentOutOfRangeException: day must be > 0 and <8; day=9
    

    [Solution and Project name: Lesson_6Task1, file name L6Task1.cs]

    Sequences

    Task 2:

    To do: Create a sequence of N integral numbers starting with a.
    a and N are entered natural numbers.
      
    Expected output:

    Please, enter two natural numbers N and a:
    2
    5
    The result:
    2 3 4 5 6
    

    [Solution and Project name: Lesson_6Task2, file name L6Task2.cs]

    Task 3:

    To do: A sequence of positive and negative integers in the range [-5;5] is given. Create a query to filter out:
    1) the positives from that sequence
    2) the elements divisible by 5
    3) odd elements.
    Note: to have the step you can use where query with a lambda expression like this:

    ... .Where(a => ...); 

    Think of what it can be there, instead of ....
      
    Expected output:

    The sequences:
    -5 -4 -3 -2 -1 0 1 2 3 4 5
    1) 1 2 3 4 5
    2) -5 0 5
    3) -5 -3 -1 1 3 5

    [Solution and Project name: Lesson_6Task3, file name L6Task3.cs]

    Task 4:

    To do: Create a sequence of 9 integral numbers in the range [1,10]. After, change the sequence making a shift of elements to the range [3,12].
    Note: to have a shift you can use select query with a lambda expression like this:

    ... .Select(a => ...); 

    Think of what it can be there, instead of ....
      
    Expected output:

    1 2 3 4 5 6 7 8 9 10
    The result:
    3 4 5 6 7 8 9 10 11 12
    

    [Solution and Project name: Lesson_6Task4, file name L6Task4.cs]