Содержание:
Lesson # 1. Introduction C# sharp in Visual Studio
Lecture in .pdf format
Theory. Microsoft Visual Studio IDE: Creating a new empty project
- Open Microsoft Visual Studio (2019 or 2022).
- To create a new solution for console these items must be chosen: (C#, All platforms, Console)
- Give a name to the created solution (the field Solution Name) and project (the field Name (Имя)).
- 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
Main Function
of the main cs
file (it is called "Program.cs"
by deafalt).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.
- For example, to add a new
.cs
file to the project with a nametask2-L1.cs
: - The result is:
- Place your cursor immediately after the open curly brace in the
Main
function, then press enter to create a new line. Place your code: - To exclude the file from the project, for example, to exclude the
program.cs
file: - Don’t forget to place the text of the task as a comment before the program:
[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 the
hw.cs
file are a surrounding structure (list of global namespace connections): - Create a code that displays the phrase «Hello, world» into the console. You have to use the following algorithm:
- Start debugging:
- To see a console window you should use
[CTRL]+F5
keybort shortcut (to start the application without debugging). If you press justF5
, you can run the program without debugging. In this case you have to add aConsole.ReadKey();
method into the code: - 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, use you right-click mouse on the
hw.cs
file tab and select Open folder option: - Find a
hw.cs
file and upload it into the moodle system:
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 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 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 L1WF1.cs
]
Algorithm:
- Open Visual Studio.
- Create a new console application (you can read how it can be done in the Theory section or Lab 0)
- Give a name to your project: it must be
Lesson_1Lab_1
- Choose a location to store the project
- Click an OK button and Visual Studio will create a new C# Console application and open
Program.cs
for you in the editor window. - Find the
Program.cs
file in the Solution Explorer window and rename it into"L1WF1.cs"
. - Place your cursor immediately after the open curly brace of the
Main
method, then press[enter]
to create a new line - 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:
- After, output the results to the Console window:
- Press the
CTRL+F5
keys to run 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 (see in Lab 0 how to do it properly) and upload the
L1WF1.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 L1WF2.cs
]
Expected output:
Input the number, please 5 The result: 6
Algorithm:
- Open Visual Studio.
- Create Console Application with the name
Lesson_1Lab2
. - 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 (to 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 (see in Lab 0 how to do it properly) and upload theL1Lab2.cs
file.
//... 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_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
).
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
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 a name
Lesson_1Lab3
. - In a Solution Explorer window find a
Program.cs
file and rename it intoL1Lab3.cs
. - Inside a
Main
function ask user to input three numbers: - Add the declaration code for three integer variables (
A
,B
,C
) to store input data; 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. Upload the file into the
moodle
system (L1Lab3.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 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