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

Дата изменения: 18 февраля 2021
Programming on c sharp in Microsoft Visual Studio. Using Console Application

Lesson # 1. Introduction C# sharp in Visual Studio

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

  1. Open Microsoft Visual Studio.
  2. The menu item File —> New —> Project (Файл -> Создать -> Проект).
  3. In the window that opens, find Visual C# in the New Project Types section. From the Templates (Шаблоны) section, select Console Application (Консольное приложение).
  4. Name the new solution (the field Solution Name) and call the project (the field Name (Имя)).
  5. Save the project to a local disk in an easily accessible location (for example, D:\Projects).
  6. Uncheck the Create directory for solution (Создать каталог для решения) checkbox to avoid multiplying directories unnecessarily.

To add new files to the project and Exclude the files

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 .cw file to the project with a name task2-L1.cs:
  2. The result is:
  3. Select the Program.cs file in the Solution Explorer window, copy code of the Main function and paste it to a new file. The result has to be so:

  4. Paste the code into task2-L1:

  5. The result is:
  6. Place your cursor immediately after the open curly brace in the Main method, then press enter to create a new line. Place your code:
  7. Exclude the file program.cs from the project to avoid the error (two Main functions cant exist in one project):
  8. 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 hw.cs files is 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. Write a program that displays the phrase «Hello, world» into the console. Use the algorithm and help pictures below:
    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 line of code with commands 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 console window use [CTRL]+F5 keybort shortcut (to start the application without debugging) or Console.ReadKey(); method:
    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, find the solution folder on the computer (d:\Projects\helloWorld\) and upload the hw.cs file:
    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 Program.cs]

    Algorithm:

    1. Open Visual Studio.
    2. Select File -> New -> Project
    3. From the Templates section, select Visual C#
    4. Select Console Application
    5. Name your project, such as Lesson_1Lab_1
    6. Choose a location to store the project
    7. Click the OK button and Visual Studio will create a new C# Console application project and open Program.cs for you in the editor window.
    8. Place your cursor immediately after the open curly brace in the Main method, then press [enter] to create a new line
    9. Enter the following code to create variables of different data types, assign values. Take a close look at which keyword is used to define a variable of this or that type:
    10. // 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);
      
    11. Output the results to the Console window:
    12. // 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}");
      
    13. Press the CTRL+F5 keys to start the application without debugging, or, use the menus, select Debug then Start Without Debugging.
    14. This will cause Visual Studio to compile the code and run the application. A console window will open results if no errors are encountered.
    15. Save the project. To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_1Lab_1\) and upload the Program.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 the 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 L1Lab2.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: File -> New -> Project/Solution -> Console Application.
    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 (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 on the computer (d:\Projects\Lesson_1Lab2\) and upload the file L1Lab2.cs.
    Task 2 for Lesson #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_1Task2, file name L1Task2.cs]

    Expected output:

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


    Note: In order for a result of the 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 3 for Lesson #1:

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

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

    double root = Math.Sqrt(3);

     
    [Solution and Project name: Lesson_1Task3, file name L1Task3.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 the name Lesson_1Lab3: File -> New -> Project/Solution -> Console Application.
    3. In the Solution Explorer window find a Program.cs file and rename it into L1Lab3.cs.
    4. Inside the 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) and 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. To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_1Lab3\) and upload the L1Lab3.cs file.
    Task 4 for Lesson #1:

    To do: Four numbers are given: x1, x2, x3, x4. Print 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_1Task4, file name L1Task4.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
    

    Windows Forms Applications

    To create a Windows Forms Applications in Visual Studio 2019:
    Lab 4. TextBox

    To do: Create Windows Forms Application to calculate an addition of three entered integeres by clicking the button.
      
    [Solution and Project name: Lesson_1Lab4, form name L1Lab4.cs]
      
    Expected output:

    ✍ Algorithm:

    Controls:

    control element name property value text property value
    form Calculation
    button btnExit Exit
    textbox txtA 0
    textbox txtB 0
    textbox txtC 0
    textbox txtSumma 0
    button btnCount Calculate
    1. Note! Give the names to the controls as it is in the specification of C# language and as it is always written in the lab or in the table above.
    2. Create new project (File → New → Project → Windows Forms Application ), and give it a name — >Lesson_1Lab4; the form of the project must be named as frmSum (Properties window → (Name) property).
    3. Add an Exit (name — btnExit) button to the form and program it. To do it use the Toolbox window → find button control and make a double click on it. The button has appeared on the form. To program this button make a double click on it. A new tab with a code has opened. Enter the code:
    4.  private void btnExit_Click(object sender, EventArgs e)
              {
               // here is your code:
                  this.Close(); 
              }
      
      this means the form itself. Besides, you can use here fust close method:

      Close();
      
    5. Start debugging and check to see if the button «works» properly.
    6. Return to the tab with the form design. Create three Textbox controls (txtA, txtB, txtC) to input integers. Set the Text property for these controls to 0 (Properties window → Text).
    7. Add one more TextBox control (txtSumma) (place it on the form as it is in a figure above).
    8. Create a Calculate button (btnCount).
    9. Program Click event for this button (make a double click on this button to program the event):
    10. private void btnCount_Click(object sender, EventArgs e)
              {
             // here your code starts
                  int summa = Int32.Parse(txtA.Text) + 
                     Int32.Parse(txtB.Text) + Int32.Parse(txtC.Text);
                  txtSumma.Text = summa.ToString();
             // here your code has finished
              }
      
      Int and Parse methods are used to convert entered string to integer type
    11. Add the captions for your buttons («Calculate» and «Exit»), changing their Text property.
    12. Run the program, enter three integers and click the Calculate button.
    13. Save your project. Find the project folder on your computer, archive it, and upload this archive to the Moodle system
    Extra task.
    Create a Windows forms Application to calculate:

    • the area of a triangle using its three sides;
    • percentage of the number.

    [Solution and Project name: Lesson_4ExTask0, form name L4ExTask0.cs]

    To students of SFEDU: follow the hyperlink to watch the lesson in Teams

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

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

    *
    *


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