Содержание:
Lesson # 1. Introduction C# sharp in Visual Studio
Theory. Microsoft Visual Studio IDE: Creating a new empty project
- Open Microsoft Visual Studio.
- The menu item File —> New —> Project (Файл -> Создать -> Проект).
- In the window that opens, find Visual C# in the New Project Types section. From the Templates (Шаблоны) section, select Console Application (Консольное приложение).
- Name the new solution (the field Solution Name) and call the project (the field Name (Имя)).
- Save the project to a local disk in an easily accessible location (for example, D:\Projects).
- 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.
- For example, to add a new
.cw
file to the project with a nametask2-L1.cs
: - The result is:
- Select the
Program.cs
file in the Solution Explorer window, copy code of theMain
function and paste it to a new file. The result has to be so: - The result is:
- Place your cursor immediately after the open curly brace in the
Main
method, then press enter to create a new line. Place your code: - Exclude the file
program.cs
from the project to avoid the error (twoMain
functions cant exist in one project): - Don’t forget to place the text of the task as a comment before the program:
Paste the code into task2-L1
:
[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 debuggingTheory. 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
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 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:
- Open Visual Studio.
- Create a new console project with a name
HelloWorld
(read the Theory). - In the Solution Explorer window find a
Program.cs
file and rename it intohw.cs
: - The first lines of the code in
hw.cs
files is a surrounding structure (list of global namespace connections): - Write a program that displays the phrase «Hello, world» into the console. Use the algorithm and help pictures below:
- Start debugging:
- To see console window use
[CTRL]+F5
keybort shortcut (to start the application without debugging) orConsole.ReadKey();
method: - Start debugging again. Save the solution. To save all the files you should use the button:
- Don’t forget to place the text of the task as a comment before the program:
- To upload the file into the moodle system, find the solution folder on the computer (
d:\Projects\helloWorld\
) and upload thehw.cs
file:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; |
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 Main(string[] args) { Console.WriteLine("Hello world!"); } //...
Console.WriteLine(...); |
if you have to output the value of the variable:
Console.WriteLine(x); |
//... static Main( [] args) { Console.WriteLine("hello World!!!"); Console.ReadKey(); } //...
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:
- Open Visual Studio.
- Select File -> New -> Project
- From the Templates section, select Visual C#
- Select Console Application
- Name your project, such as
Lesson_1Lab_1
- Choose a location to store the project
- 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. - Place your cursor immediately after the open curly brace in the
Main
method, then press [enter] to create a new line - 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:
- Output the results to the Console window:
- Press the
CTRL+F5
keys to start the application without debugging, or, use the menus, select Debug then Start Without Debugging. - This will cause Visual Studio to compile the code and run the application. A console window will open results if no errors are encountered.
- 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 theProgram.cs
file.
// create variables of different data types // initialize them with the default values firstname = ""; lastname = ""; age = 0; city = ""; country = ""; DateTime birthDate; // Assign some values firstname = "Alex"; lastname = "Ivanov"; age = 18; city = "anyTown"; country = "myCountry"; birthDate = DateTime (1991, 1, 6);
// 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}");
- To input some data a standart
ReadLine()
method should be used: - To input data and set it to the integer variable
n
: - 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
):
Console.ReadLine() |
1.
int n = int.Parse(Console.ReadLine()); |
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()); |
String s = Console.ReadLine(); int n = int.Parse(s); |
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:
- Open Visual Studio.
- Create Console Application with the name
Lesson_1Lab2
: File -> New -> Project/Solution -> Console Application. - In the Solution Explorer window find a
Program.cs
file and rename it intoL1Lab2.cs
. - Inside the
Main
function ask user to input a number: - Add the declaration code for an integer variable
n
and request a value for it (input): - Add a code to increment the variable by one and output its value. Then place an operator to delay the console window:
- In General, the file code should look like this:
- Start debugging the application (
F5
). - Don’t forget to place the text of the task as a comment before the main code.
- 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 fileL1Lab2.cs
.
//... static Main(string[] args) { Console.WriteLine("Input a number, please"); } //...
//... Console.WriteLine("Input a number, please"); int n = int. (Console.ReadLine()); //...
//... n++; Console.WriteLine(n); Console.ReadKey(); //...
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson_1 { L1Lab2 { static Main(string[] args) { Console.WriteLine("Input a number, please"); int n = int. (Console.ReadLine()); n++; Console.WriteLine(n); Console.ReadKey(); } } }
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
).
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
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:
- Open Visual Studio.
- Create Console Application with the name
Lesson_1Lab3
: File -> New -> Project/Solution -> Console Application. - In the Solution Explorer window find a
Program.cs
file and rename it intoL1Lab3.cs
. - Inside the
Main
function ask user to input three numbers: - Add the declaration code for three integer variables (
A
,B
,C
) and request the values for them (input): - 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
): - Run the application (
F5
). - To make the output more beautiful you can use another way (c# recommended syntax). Comment out the previous output:
- One more way to do the same is to use a boolean variable to store the result of the condition:
- Start debugging. The result will be the same but more beautiful.
- Don’t forget to place the text of the task as a comment before the main code.
- Save the project. To upload the file into the
moodle
system, find the solution folder on the computer (d:\Projects\Lesson_1Lab3\) and upload theL1Lab3.cs
file.
//... static Main(string[] args) { Console.WriteLine("Input three numbers, please"); } //...
//... Console.WriteLine("Input three numbers, please"); int a = int. (Console.ReadLine()); int b = int. (Console.ReadLine()); int c = int. (Console.ReadLine()); //...
&&
which means AND
:
A < B && B < C
//... Console.WriteLine(a<b && b<c); Console.ReadKey(); //...
//... //Console.WriteLine(a<b && b<c); Console.WriteLine($"{a}<{b}<{c}={a < b && b<c}"); Console.ReadKey(); //...
//... bool d = (a < b) && (b < c); Console.WriteLine($"{a}<{b}<{c}={d}"); //...
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 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:
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 |
- 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.
- 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).
- 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:
- Start debugging and check to see if the button «works» properly.
- 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).
- Add one more TextBox control (txtSumma) (place it on the form as it is in a figure above).
- Create a Calculate button (btnCount).
- Program Click event for this button (make a double click on this button to program the event):
- Add the captions for your buttons («Calculate» and «Exit»), changing their Text property.
- Run the program, enter three integers and click the Calculate button.
- Save your project. Find the project folder on your computer, archive it, and upload this archive to the Moodle system
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();
private void btnCount_Click(object sender, EventArgs e) { // here your code starts int summa = Int32. (txtA.Text) + Int32. (txtB.Text) + Int32. (txtC.Text); txtSumma.Text = summa.ToString(); // here your code has finished }
Int
and Parse
methods are used to convert entered string to integer typeCreate 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