Lesson # 1. Programming on c sharp in Microsoft Visual Studio

Programming on c sharp in Microsoft Visual Studio. Using Console Application

Lesson # 1. Introduction C# sharp in Visual Studio

Lecture in .pdf format

Theory. Microsoft Visual Studio IDE: Creating a new empty project

  1. Open Microsoft Visual Studio (2019 or 2022).
  2. To create a new solution for console these items must be chosen: (C#, All platforms, Console)
  3. Give a name to the created solution (the field Solution Name) and project (the field Name (Имя)).
  4. Save the project to a local disk in an easily accessible location (for example, D:\Projects).

To add new files to the project and Exclude the files

  • The basic code of your program should be inside a Main Function of the main cs file (it is called "Program.cs" by deafalt).
  • It is better to rename this file (mouse right-click on the Program.cs file in the Solution Explorer window -> Rename)
  • You can add new files to the project (right-click on the project in the Solution Explorer window (Обозреватель решений) —> Add -> New Item (Создать элемент). For this and any other project, you will need at least one file with an entry point to the program — the main function.

    1. For example, to add a new .cs file to the project with a name task2-L1.cs:
    2. The result is:

    3. Place your cursor immediately after the open curly brace in the Main function, then press enter to create a new line. Place your code:
    4. To exclude the file from the project, for example, to exclude the program.cs file:
    5. Don’t forget to place the text of the task as a comment before the program:
    Keyboard shortcuts

  • [CTRL]+k+c — commenting a block of code
  • [CTRL]+k+u — uncommenting a block of code
  • [F5] — to execute the program
  • [CTRL]+F5 — to start the application without debugging
  • Theory. C# Syntax: Statements

    In C#, a statement is considered a command. Statements perform some action in your code such as calling a method or performing calculations. Statements are also used to declare variables and assign values to them.

    Statements are formed from tokens. These tokens can be keywords, identifiers (variables), operators, and the statement terminator which is the semicolon (;). All statements in C# must be terminated with a semicolon.

    Example:

    int myVariable = 2;

    In this example, the tokens are:

  • int
  • myVariable
  • =
  • 2
  • ;
  • int is the data type used for the variable called myVariable.

    The ‘=‘ is an assignment operator and is used to set the value of myVariable to 2.

    The numeral 2 is known as a literal value. Literal simply means that it is, what it says it is. The numeral 2 cannot be anything but the numeral 2. You cannot assign a value to 2. You can assign the numeral 2 to a variable however, and that is what this C# statement is doing.

    Finally, the statement ends with a semi-colon.

    C# Syntax: Identifiers

    In C#, an identifier is a name you give to the elements in your program. Elements in your program include:

    • Namespaces — the .NET Framework uses namespaces as a way to separate class files into related buckets or categories. It also helps avoid naming collisions in applications that may contain classes with the same name
    • Classes — classes are the blueprints for reference types. They specify the structure an object will take when you create instances of the class
    • Methods — they are discrete pieces of functionality in an application. They are analogous to functions in the non-object-oriented programming world
    • Variables — these are identifiers or names, that you create to hold values or references to objects in your code. A variable is essentially a named memory location

    When you create a variable in C# you must give it a data type. The data type tells the compiler and syntax checker what kind of information you intend to store in that variable. If you try to assign data that is not of that type, warnings or errors will inform you of this. This is part of the type-safe nature of C#.

    You can assign a value to the variable at the time you create it or later in your program code. C# will not allow you to use an unassigned variable to help prevent unwanted data from being used in your application. The following code sample demonstrates declaring a variable and assigning a value to it.

    int myVar = 0;

    C# has some restrictions around identifiers that you need to be aware of.

    First off, identifiers are case-sensitive because C# is a case-sensitive language. That means that identifiers such as myVar, _myVar, and myvar, are considered different identifiers.

    Identifiers can only contain letters (upper case or lowercase), digits, and the underscore character. You can only start an identifier with a letter or an underscore character. You cannot start the identifier with a digit. myVar and _myVar are legal but 2Vars is not.

    C# has a set of reserved keywords that the language uses. You should not use these keywords as an identifier in your code. You may choose to take advantage of the case-sensitivity of C# and use Double as an identifier to distinguish it from the reserved keyword double, but that is not a recommended approach.

    C# Syntax: Operators

    When writing C# code, you will often use operators. An operator is a token that applies to operations on one or more operands in an expression. An expression can be part of a statement, or the entire statement. Examples include:

    3 + 4 – an expression that will result in the literal value 4 being added to the literal value 3

    counter++ – an expression that will result in the variable (counter) being incremented by one

    Not all operators are appropriate for all data types in C#. As an example, in the preceding list the + operator was used to sum two numbers. You can use the same operator to combine two strings into one such as:

    “Tom” + “Sawyer” which will result in a new string TomSawyer

    You cannot use the increment operator (++) on strings however. In other words, the following example would cause an error in C#.

    “Tom”++

    The following table lists the C# operators by type.

    Type Operators

    Arithmetic

    +, -, *, /, %

    Increment, decrement

    ++, —

    Comparison

    ==, !=, <, >, <=, >=, is

    String concatenation

    +

    Logical/bitwise operations

    &, |, ^, !, ~, &&, ||

    Indexing (counting starts from element 0)

    [ ]

    Casting

    ( ), as

    Assignment

    =, +=, -=, =, /=, %=, &=, |=, ^=, <<=, >>=, ??

    Bit shift

    <<, >>

    Type information

    sizeof, typeof

    Delegate concatenation and removal

    +, —

    Overflow exception control

    checked, unchecked

    Indirection and Address (unsafe code only)

    *, ->, [ ], &

    Conditional (ternary operator)

    ?:

    Labs and Tasks

    Console Applications

    To create a console application in visual studio 2019:
    Lab 0:

    To do: Create a simple console application that displays a «Hello world!» phrase into the console window.

    [Solution and Project name: HelloWorld, file name hw.cs]

    Algorithm:

    1. Open Visual Studio.
    2. Create a new console project with a name HelloWorld (read the Theory).
    3. In the Solution Explorer window find a Program.cs file and rename it into hw.cs:
    4. The first lines of the code in the hw.cs file are a surrounding structure (list of global namespace connections):
    5. using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
    6. Create a code that displays the phrase «Hello, world» into the console. You have to use the following algorithm:
    7.     5.1. Make sure that the hw.cs file is active in the Solution Explorer window.
          5.2. To output something in the console you should use a Console.WriteLine(...); method. Each statement must end with a semicolon.
          5.3. Add the method into the correct place of the code: Place your cursor immediately after the open curly brace in the Main method, then press [enter] to create a new line:

      //...
      static void Main(string[] args)
              {
                   Console.WriteLine("Hello world!");
              }
      //...
      

    8. Start debugging:
    9. To output into the console window:

      Console.WriteLine(...);

      if you have to output the value of the variable:

      Console.WriteLine(x);
    10. To see a console window you should use [CTRL]+F5 keybort shortcut (to start the application without debugging). If you press just F5, you can run the program without debugging. In this case you have to add a Console.ReadKey(); method into the code:
    11. //...
      static void Main(string[] args)
              {
                  Console.WriteLine("hello World!!!");
                  Console.ReadKey();
              }
      //...
      
    12. Start debugging again. Save the solution. To save all the files you should use the button:
    13. Don’t forget to place the text of the task as a comment before the program:
    14. To upload the file into the moodle system, use you right-click mouse on the hw.cs file tab and select Open folder option:
    15. Find a hw.cs file and upload it into the moodle system:
    Lab 1:

    To do: Create the variables of different data types, initialize them with the default values, assign some values, output to the console window.

    [Solution and Project name: Lesson_1Lab_1, file name L1WF1.cs]

    Algorithm:

    1. Open Visual Studio.
    2. Create a new console application (you can read how it can be done in the Theory section or Lab 0)
    3. Give a name to your project: it must be Lesson_1Lab_1
    4. Choose a location to store the project
    5. Click an OK button and Visual Studio will create a new C# Console application and open Program.cs for you in the editor window.
    6. Find the Program.cs file in the Solution Explorer window and rename it into "L1WF1.cs".
    7. Place your cursor immediately after the open curly brace of the Main method, then press [enter] to create a new line
    8. Enter the following code to create the variables of different data types, assign values (replacing by your own). Take a close look at which keyword is used to define a variable of a specified type:
    9. // create variables of different data types
      // initialize them with the default values
      string firstname = "";
      string lastname = "";
      int age = 0;
      string city = "";
      string country = "";
      DateTime birthDate;
      
      // Assign some values
      firstname = "Alex";
      lastname = "Ivanov";
      age = 18;
      city = "anyTown";
      country = "myCountry";
      birthDate = new DateTime (1991, 1, 6);
      
    10. After, output the results to the Console window:
    11. // use simple output with just variable name
      Console.WriteLine(firstname);
      Console.WriteLine(lastname);
      
      // use placeholder style
      Console.WriteLine("{0} years old.", age);
      
      //use string concatenation
      Console.WriteLine(city + ", " + country);
      
      //use string interpolation
      Console.WriteLine($"Born on {birthDate}");
      
    12. Press the CTRL+F5 keys to run the application without debugging, or, use the menus, select Debug then Start Without Debugging.
    13. This will cause Visual Studio to compile the code and run the application. A console window will open results if no errors are encountered.
    14. Save the project. To upload the file into the moodle system, find the solution folder (see in Lab 0 how to do it properly) and upload the L1WF1.cs file.
    Input data

    • To input some data a standart ReadLine() method should be used:
    • Console.ReadLine()
    • To input data and set it to the integer variable n:
    • 1.

      int n = int.Parse(Console.ReadLine());
      where int means integer type of the variable n;
      int.Parse — method to transform string type of the inputted data into integer type.

      2.

      int n = Convert.ToInt32(Console.ReadLine());
    • The same you should do if you use two variables: at first, the inputted data is set to a string variable (s), afterward this value is converted into integer and set to integer type variable (n):
    • String s = Console.ReadLine();
      int n = int.Parse(s);
    Lab 2. Increasing a number by one

    To do: Ask user to input a number. Increase the inputted number by one. Output the result.

    [Solution and Project name: Lesson_1Lab2, file name L1WF2.cs]
      
    Expected output:

    Input the number, please
    5
    The result: 6
    

    Algorithm:

    1. Open Visual Studio.
    2. Create Console Application with the name Lesson_1Lab2.
    3. In the Solution Explorer window find a Program.cs file and rename it into L1Lab2.cs.
    4. Inside the Main function ask user to input a number:
    5. //...
      static void Main(string[] args)
       {
          Console.WriteLine("Input a number, please");
       }
      //...
      
    6. Add the declaration code for an integer variable n and request a value for it (to input):
    7. //...
        Console.WriteLine("Input a number, please");
        int n = int.Parse(Console.ReadLine());
      //...
      
    8. Add a code to increment the variable by one and output its value. Then place an operator to delay the console window:
    9. //...
      n++;
      Console.WriteLine(n);
      Console.ReadKey();
      //...
      
    10. In General, the file code should look like this:
    11. using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      
      namespace Lesson_1
      {
          class L1Lab2
          {
              static void Main(string[] args)
              {
                  Console.WriteLine("Input a number, please");
                  int n = int.Parse(Console.ReadLine());
                  n++;
                  Console.WriteLine(n);
                  Console.ReadKey();
              }
          }
      }
      
    12. Start debugging the application (F5).
    13. Don’t forget to place the text of the task as a comment before the main code.
    14. Save the project. To upload the file into the moodle system, find the solution folder (see in Lab 0 how to do it properly) and upload the L1Lab2.cs file.
    Task 1:

    To do: Create a console application that calculates the arithmetic mean (average) of two given integers and outputs a result to the console window.

    [Solution and Project name: Lesson_1Task1, file name L1Task1.cs]

    Expected output:

    Please, input two integers:
    2  6
    The average is 4
    


    Note: In order for a result of a division to be performed in a real type, one of the operands must be real (double type in c#). The easiest way to achieve this is to use 2.0 as a divisor (e.g. (a + b) / 2.0).

    Task 2:

    To do: Ask user to enter a triangle side. Calculate a perimeter and area of the triangle.
      
    Note 1: The formula of area is:

    Note 2: To calculate a square root the Math class should be used, e.g.:

    double root = Math.Sqrt(3);

     
    Note 3: To calculate a power of a number the Math class should be used as well, e.g.:

    Math.Pow(baseNumb, exponent);

    [Solution and Project name: Lesson_1Task2, file name L1Task2.cs]

    Expected output:

    Enter a side of triangle, please:
    >> 3
    Perimeter of the triangle: 9
    Area:  3.89711431702997
    

    Lab 3. Boolean type

    To do: Three integers are given: A, B and C (they are input). Output a true value to the console window if the double inequality A < B < C is true, and output false otherwise.
      
    Note: do not use the conditional operator.

    [Solution and Project name: Lesson_1Lab3, file name L1Lab3.cs]
      
    Expected output:

    Input three numbers, please
    5  7  10
    The result: true
    
    Input three numbers, please
    8  7  10
    The result: false
    

    Algorithm:

    1. Open Visual Studio.
    2. Create Console Application with a name Lesson_1Lab3.
    3. In a Solution Explorer window find a Program.cs file and rename it into L1Lab3.cs.
    4. Inside a Main function ask user to input three numbers:
    5. //...
      static void Main(string[] args)
       {
          Console.WriteLine("Input three numbers, please");
       }
      //...
      
    6. Add the declaration code for three integer variables (A, B, C) to store input data; request the values for them (input):
    7. //...
        Console.WriteLine("Input three numbers, please");
        int a = int.Parse(Console.ReadLine());
        int b = int.Parse(Console.ReadLine());
        int c = int.Parse(Console.ReadLine());
      //...
      
      To use two or more comparative operators in C# you must have logic operator && which means AND:

      A < B && B < C
    8. Add a code to output a result of a double comparison of the variables to the console window (if a < b and b < c the result will be true, and otherwise — false):
    9. //...
      Console.WriteLine(a<b && b<c);
      Console.ReadKey();
      //...
      
    10. Run the application (F5).
    11. To make the output more beautiful you can use another way (c# recommended syntax). Comment out the previous output:
    12. //...
      //Console.WriteLine(a<b && b<c);
      Console.WriteLine($"{a}<{b}<{c}={a < b && b<c}");
      Console.ReadKey();
      //...
      
      In this case, you must use the $ symbol. There are the placeholders in the curly brackets, they are for the values of variables.
    13. One more way to do the same is to use a boolean variable to store the result of the condition:
    14. //...
      bool d = (a < b) && (b < c);
      Console.WriteLine($"{a}<{b}<{c}={d}");
      //...
      
    15. Start debugging. The result will be the same but more beautiful.
    16. Don’t forget to place the text of the task as a comment before the main code.
    17. Save the project. Upload the file into the moodle system (L1Lab3.cs file).
    Task 3:

    To do: Four numbers are given: x1, x2, x3, x4. Print out true if a sum of the first two numbers (x1, x2) is greater than a sum of the next two numbers (x3, x4), and print false otherwise.
      
    Note: Do not use a conditional operator.
     
    [Solution and Project name: Lesson_1Task3, file name L1Task3.cs]

    Expected output:

    Please, input four integers:
    2  6  5  1
    The result: true
    
    Please, input four integers:
    2  6  5  7
    The result: false
    

    —>