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

Programming on c sharp in Microsoft Visual Studio. Creating Generic Methods.

Lesson # 8. Theory

Lecture in pdf format

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:
  •     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 the symbol which was entered. 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).

Expected output:

please input a number:
2
result: 2 2 2 2 2 2 2 2 2 2 

please input a symbol:
*
result: * * * * * * * * * *

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

✍ How to do:

  • Within the Main function request the user to input a symbol. At first, input integer value:
  • ...
    Console.WriteLine("please input a number");
    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 a 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.


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 class with Main function. Calling the methods of the created class has to be organized inside the Main function.
To do: Add a new class named MyFuncs to a project of your solution. Copy a PrintSymbol method (created in the previous lab) and paste it into this class.

Expected output:

please input a number:
2
result: 2 2 2 2 2 2 2 2 2 2 
please input a symbol:
*
result: * * * * * * * * * *

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

✍ 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 (just in case).
  • 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. In the signature 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>(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 number");
    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 L8Lab2.cs file into the moodle system.


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 an Add() function 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)

  
Expected output:

Please enter two integers 
9  8
The sum is: 17

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

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 MyFuncsLab3 to the project. Move a PrintSymbol() method to this class.

Expected output:

please input a number:
2
result: 2 2 2 2 2 2 2 2 2 2 
please input a symbol:
*
result: * * * * * * * * * *

[Solution and Project name: Lesson_8Lab2, files’ names L8Lab3.cs and myFuncsLab3.cs]

✍ 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 MyFuncsLab3 name.
  • Make sure that the new MyFuncsLabs.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 MyFuncsLab3 (of the MyFuncsLab3.cs file). We don’t need the keyword static anymore, only public keyword. Clear up the static:
  • class MyFuncsLab3
        {
            public void PrintSymbol <T>(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.
  • After, to call the method PrintSymbol we have to use dot-notation and the myClass class:
  • ...
    MyFunctsLab3.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 MyFuncsLab3.csinto the moodle system.

Task 2:

To do: An array of integers is given (10 elements with random generated 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 FillRandomArray() function to fill the array with random values.
Note 3: Create a function named Print to output the array’s elements.
Note 4: Create a FindEven() function to find and print the even elements of the array. The method takes arr parameter (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)
  {
  }

     
Expected output:

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

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


Task 3:

To do: An array of integers is given ({ 1, 2, 7, -3, 4 }). Create a new class called MyFunctions within the same file where Main class is.
1. Create a user defined method (extension method) to print out the array elements (see a lecture pdf file). Call this method using dot notation:

a.Print();

2. Create a user defined method (extension method) to make a shift left algorithm (see a lecture pdf file). Call this method using dot notation:

a.ShiftLeft();

     
Expected output:

Array: 
1, 2, 7, -3, 4
Shifted left array:
2, 7, -3, 4, 0

[Solution and Project name: Lesson_8Task3, files’ names L8Task3.cs]