Lesson # 8. Generic Methods. Solution, project, assembly. Adding a class

Дата публикации: 12 февраля 2020
Programming on c sharp in Microsoft Visual Studio. Creating Generic Methods.

Lesson # 8. Theory

Creating Generic Methods

    In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.

  • The task is to swap the values of two variables. The variables can be of different types. A generic method is a method that is declared with type parameters, as follows:
  • static void Swap<T>(ref T lhs, ref T rhs)
    {
        T temp;
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }

    <T> means any type.

  • The following code example shows one way to call the method by using int for the type argument:
  • public static void TestSwap()
    {
        int a = 1;
        int b = 2;
     
        Swap<int>(ref a, ref b);
        System.Console.WriteLine(${a}  {b}");
    }
  • Or a simple way to call the method:
  • Swap(ref a, ref b);

Solution, Project, Assembly

  • Once we create a project, a solution is created at the same time. An extension of a project is .csproj, an extension of a solution is .sln.
  • A solution can include more than one project, we can add new projects to a solution.
  • The result of compiling the project is an Assembly. Assembly is a compiled application. Depending on its type it is .exe file (console application) or .dll file (class library).
  • An application consists of building blocks called classes.There can be many classes in one project.
  • Namespace is a container for related classes.
  • Assembly is a container for namespaces.
  • To add a new class:

Labs and tasks

Lab 1. Creating a Generic method

To do: Create a generic function named PrintSymbol to output 10 times inputted symbol. Call the function two times: with integer parameter and string parameter.

Note: The PrintSymbol function takes one argument — entered symbol (T argument) and returns no value (which is why you have to use void).

[Solution and Project name: Lesson_8Lab1, file name L8Lab1.cs]

The result examples:

please input a symbol:
2
result: 2 2 2 2 2 2 2 2 2 2 
please input one more symbol:
*
result: * * * * * * * * * *

  


✍ How to do:

  • Within the Main function request the user to input a symbol. At first, input integer value:
  • ...
    Console.WriteLine("please input a symbol");
    int symbolInt = Int32.Parse(Console.ReadLine());
    ...
    
  • Declare a new generic method called PrintSymbol() that will be used to output value passed into it. To make the method generic <T> is required:
  • ...
    static void PrintSymbol <T>(T symbol)
    {
        ...
    }
    ...
    
  • Place a code to print out the entered symbol. Use for loop:
  • ...
    for (int i=0; i < 10; i++)
                {
                    Console.Write($"{symbol} ");
                }
    ...
    
  • Now we can call this method from within the Main function. Enter the following code within the curly braces of Main():
  • ...
    PrintSymbol(symbolInt);
    
  • Press the CTRL+F5 keys to start the application without debugging.
  • Now we are going to call this method with a string parameter. First, declare a variable of a string type and initialize it with the inputted value:
  •  ...
     Console.WriteLine("please input one more symbol:");
     string symbolStr = Console.ReadLine();
     PrintSymbol(symbolStr);
    
  • Run the application again and check the output. Save the solution and upload the file into the moodle system.


It would be better to watch the video, how to do:


Lab 2. Adding a new class to the project within the same namespace

Explanation: As the complexity of the project increases, it becomes necessary to add a new class to store methods there. Creating a new class can be organized within the same cs file, after the code of the Main class. Calling the methods has to be organized inside the Main function.
To do: Add a new class named MyFuncs to a project of a new solution. Move a method PrintSymbol to this class.

[Solution and Project name: Lesson_8Lab2, file name L8Lab2.cs]

The result examples:

please input a symbol:
2
result: 2 2 2 2 2 2 2 2 2 2 
please input one more symbol:
*
result: * * * * * * * * * *


✍ How to do:

  • Open the solution of the previous lab (Lesson_8Lab1). Copy the code of the PrintSymbol method and paste it temporarily to some text file.
  • Create a new console application with the name Lesson_8Lab2. Rename the program.cs file to L8Lab2.cs.
  • Place your cursor immediately after the close curly brace of the L8Lab2 class.
  • Type the code to create a new class with the name MyFuncs:
  •  class L8Lab2
        {
            static void Main(string[] args)
            {
              ...
            }
        }
    // your code is down here
        class MyFuncs
        {
        }
    
  • Copy the code of the PrintSymbol method (you have it in a temporary text file) and paste it after the open curly brace of class MyFuncs. Within a code of the PrintSymbol method along with the keyword static, add a public keyword, to make the method accessible in all the project’s classes and namespaces:
  • ...
    class MyFuncs
        {
            public  static void PrintSymbol(T symbol)
            {
                for (var i = 0; i < 10; i++)
                {
                    Console.Write($"{symbol} ");
                }
    
            }
        }
    
  • Within the Main function request the user input a symbol:
  • ...
    Console.WriteLine("please input a symbol");
    int symbolInt = Int32.Parse(Console.ReadLine());
    ...
    
  • To call the function within the Main method we have to do it using the MyFuncs class:
  • ...
    MyFuncs.PrintSymbol(symbolInt); 
    ...
  • Run the application and check the output, it has to be similar to as it was in the previous Lab.
  • Save the application and upload the file L8Lab2.cs into the moodle system.

If something is not clear it is better to watch the video of how to do this lab:


Task 1:

To do: Create a new class with the name MyFuncs. Within the created class add a method with the name Add which sums up two numbers.

Note: Create a function Add with two arguments. The function must return addition of these arguments. Call the function within the Main method. The signature of the function should be as follows:

public static int Add(int i, int j)

     
[Solution and Project name: Lesson_8Task1, file name L8Task1.cs
  
The result example:

Please enter two integers 
9  8
The sum is: 17

  




Lab 3. Adding a new class (file) to the project
Explanation: As the complexity of the project increases, it becomes necessary to add a new class to store methods there. A new class can be added as a new file with a new namespace. Calling the methods has to be organized inside the Main function.
To do: Open the solution of the previous work (Lesson_8Lab2). Add a new class named MyFunctions to the project. Move a method PrintSymbol to this class.

[Solution and Project name: Lesson_8Lab2, file name L8Lab3.cs]

The result examples:

please input a symbol:
2
result: 2 2 2 2 2 2 2 2 2 2 
please input one more symbol:
*
result: * * * * * * * * * *


✍ How to do:

  • Open the solution of the previous work (Lesson_8Lab2). Rename the main file into L8Lab3.
  • In the Solution Explorer (Обозреватель решений) window Click the right mouse button on the name of the project -> Add (Добавить) -> Class (Класс). Give it MyFunctions name.
  • Make sure that the new MyFunctions.cs file has appeared in the Solution explorer window.
  • Copy the code of PrintSymbol method and paste it after the open curly brace of class MyFunctions (of the MyFunctions.cs file). We don’t need the keyword static anymore, only public keyword. Clear up the static:
  • class MyFunctions
        {
            public void PrintSymbol(T symbol)
            {
                for (var i = 0; i < 10; i++)
                {
                    Console.Write($"{symbol} ");
                }
    
            }
        }
    
  • In the Solution Explorer (Обозреватель решений) window make active the main file — L8Lab3.cs, open its code in the code editor window.
  • There is no PrintSymbol method there anymore. Now we are going to create an instance of our MyFunctions class. Add the following code right at the beginning of the Main function:
  • static void Main(string[] args)
            {
                MyFunctions myClass = new MyFunctions();
                 ...
            }
    
  • After, we have to add the class myClass to call the method PrintSymbol:
  • ...
    myClass.PrintSymbol(symbolInt);
    ...
  • Run the application and check the output, it has to be similar to as it was in the previous Lab.
  • Save the application and upload the files L8Lab3.cs and MyFunctions.csinto the moodle system.

Task 2:

To do: An array of integers is given (10 elements with random values in the range from -10 to 10). Find and print the even elements of the array and their indexes, and also output the number of even elements. All functions have to be stored in added class L8MyFunctions.

  
Note 1: Add a new class called L8MyFunctions (a new file of class).
Note 2: Create a function FillRandomArray to fill the array with random values.
Note 3: Create a function named Print to output the array’s elements.
Note 4: Create a function FindEven to find and print the even elements of the array. The method takes parameter arr (the array) and returns the value of out parameter counter. The signature of the function should look like this:

public void FindEven(int[] arr, out int counter)
  {
  }

     
[Solution and Project name: Lesson_8Task2, files’ names L8Task2.cs, L8MyFunctions.cs]
  
The resulting example:

Array: 
9 8 -10 8 -1 6 2 -9 8 7 
even elements:
8, index: 1
-10, index: 2
8, index: 3
6, index: 5
2, index: 6
8, index: 8

number of even elements: 6

Поделитесь уроком с коллегами и друзьями:[SvenSoftSocialShareButtons]

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

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

*
*


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