Lesson # 6. Using methods or functions, enumerations

Дата изменения: 18 марта 2020
Programming on c sharp in Microsoft Visual Studio. Using methods or functions.

Lesson # 6. Theory

  • 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);
    

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 characteristic 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]

The resulting examples:

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.

If you still have some questions you can watch the video:


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.
  
  
[Solution and Project name: Lesson_6Task1, file name L6Task1.cs]
  
The resulting example:

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


Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

*
*


Вставить формулу как
Блок
Строка
Дополнительные настройки
Цвет формулы
Цвет текста
#333333
Используйте LaTeX для набора формулы
Предпросмотр
\({}\)
Формула не набрана
Вставить