1
.NET and C# Basics
part 2: Foundations of
Programming
[Link]
2
What you will learn :
Memory. Variables. Visibility Scope
Data Types
Arithmetical and logical operations
Conditionals
loops
Arrays
Functions
[Link]
3
Memory
Variables. Initialization
Nested and user-defined data types
Implicit typing
Visibility Scope
[Link]
4
Variables
Variable is a memory “cell” which can store information of a
certain type.
Each variable has its own address.
When declaring a variable, specify its type and name.
[Link]
5
Initializing a variable
A variable is initialized once some value is assigned to it
- declared but not initialized
- initialization. Memory allocation
[Link]
6
There are the following visibility
scopes:
Code block context
Method context
Class context
Assembly context
[Link]
7
Sequential execution blocks
Are enclosed In a child block you In the same
between curly cannot declare a level block –
braces variable with the same you can do it
name as in the parent {
{
block int i;
// code
{ ...
}
int i; }
... ...
{ {
int i; int i;
... ...
} }
}
[Link]
8
Data Types
Value and reference types
Where types are stored
Size
Primitive types
Enumerations
[Link]
9
Types of Variables
There are two kinds of types in C#: reference types and value types
Value type variables contain data as such
Reference type variables contain references to required data called
objects
[Link]
10
Value Types
Value types:
Usually placed in the stack
A variable contains data
Each variable changes its data only
Assigning = copying
[Link]
11
Reference Types
Reference types:
Memory is allocated from the bulk
Variables store a reference to data (objects)
Two reference variables can refer to the same object
Changing properties of one object results in changing the other
[Link]
12
Comparing data types
Value types Reference types
The variable The variable contains a
contains a value reference to data
directly Data is stored in a
Examples: separate memory area
char, int
int mol; string mol;
mol = 42; mol = "Hello";
42 • Hello
[Link]
13
Declaration and Release
Declaration
coordinate c1;
c1 = new coordinate();
c1.x = 6.12;
• 6.12 4.2
c1.y = 4.2;
Release
c1 = null; • 6.12 4.2
[Link]
14
Comparing values and references
Comparing value types
The operators == and != compare field values
Comparing reference types
The operators == and != compare references but not the
field values of an object
• 1.0 2.0
Different
• 1.0 2.0
[Link]
15
Multiple references to object
Multiple reference variables can refer to the same object
c1 •
2.3 7.6
c2 •
coordinate c1= new coordinate( );
coordinate c2;
c1.x = 2.3; c1.y = 7.6;
c2 = c1;
[Link](c1.x + " , " + c1.y);
[Link](c2.x + " , " + c2.y);
[Link]
16
Incorrect references
While compiling
The compiler warns about an error when it encounters the use of non-
initialized references.
While executing the program
The CLR will generate an exception when addressing an incorrect
reference.
note: Exception generating and handling will be discussed in the next Module 3 (OOP).
[Link]
17
Reference and value types. Table
[Link]
18
Data size
For the CLR all (except structures) value
data types have a fixed size irrespective
of processor architecture.
Always select a correct data type,
as its size may dramatically increase!
[Link]
19
Name and size of main reference types 1 \ 2
Short Name .NET Class Type Width Range (bits)
byte Byte Unsigned integer 8 0 to 255
sbyte SByte Signed integer 8 -128 to 127
int Int32 Signed integer 32 -2,147,483,648 to
2,147,483,647
uint UInt32 Unsigned integer 32 0 to 4294967295
short Int16 Signed integer 16 -32.768 to 32.767
ushort UInt16 Unsigned integer 16 0 to 65535
long Int64 Signed integer 64 -9223372036854775808 to
9223372036854775807
ulong UInt64 Unsigned integer 64 0 to 18446744073709551615
[Link]
20
Name and size of main reference types 2 \ 2
Short .NET Type Width Range (bits)
Name Class
float Single Single-precision floating 32 -3.402823e38 to
point type 3.402823e38
double Double Double-precision floating 64 -1.79769313486232e308
point type to 1.79769313486232e308
char Char A single Unicode character 16 Unicode symbols used in
text
bool Boolean Logical Boolean type 8 True or false
decimal Decimal Precise fractional or integral128 ±1.0 × 10e−28 to
type that can represent ±7.9 × 10e28
decimal numbers with 29
significant digits
[Link]
21
Primitive types
Are directly supported by the compiler
Have simplified syntax
-int // Reserved keyword
- or -
-System.Int32
-int a = 0; // the same as
- System.Int32 = new System.Int32(0)
[Link]
22
Check for Arithmetic Overflow
By default, C# does not check number types for overflow
The block ‘checked’ triggers the check for overflow
checked { OverflowException
int number = [Link];
[Link](++number); Exception object is thrown.
} WriteLine is not executed.
unchecked { MaxValue + 1 is negative?
int number = [Link];
[Link](++number);
} -2147483648
[Link]
23
Enumerations
Enum is a user-defined data type.
A variable of this type can take values strictly from
your list of enumerations.
By default, the first enumerator is 0, and the value of each subsequent
enumerator is increased by 1.
Cast to int 0 1 2
[Link]
24
Enumerations
Usually the best practice is to define enumeration directly in the
namespace so that all classes in the namespace can easily access
it.
Example – days of week:
[Link]
25
Operators and Statements
Relational operators and logical operators
Directive ‘using’
Output on console and input from console
Comments
Logical operators
Priority
[Link]
Relational operators and logical operators 26
== Equality
!= Inequality
> Greater than
<
Less than
>=
Greater than or equal
<=
Less than or equal
&
Integer logical bitwise AND operator
|
Integer logical bitwise OR operator
^
Integer logical bitwise XOR operator
&&
Conditional logical AND operator
||
Conditional logical OR operator
!
Logical negation operator
[Link]
27
Directive ‘using’
The directive using is used for the following three purposes :
To allow using types in the namespace so that you don’t need to
qualify using the type in this namespace
[Link]
28
Directive ‘using’
To create an alias for a namespace or type
[Link]
29
Directive ‘using’
using (SqlConnection sqlconnection = new SqlConnection(connectionString))
{
String commandString = "SELECT Id,Title FROM PEOPLE";
SqlCommand cmd = new SqlCommand(commandString, sqlconnection);
[Link]();
using (SqlDataReader reader = [Link]())
{
while ([Link]())
{
//DO
}
}
}
[Link]
30
[Link] Class
Access to standard input, output and error flows.
Valid for console applications only:
Standard input – keyboard
Standard output – screen
Standard error – screen
Standard flows can be redirected – for example, to a file
[Link]
31
Write and WriteLine Methods
[Link] and [Link] display information on the
screen
WriteLine adds new string symbols (\r\n)
Both methods are overloaded
You can use the formatting string for:
Text formatting
Numbers formatting
[Link]
32
Read and ReadLine Methods
[Link] and [Link] read user input
Read – read a symbol
ReadLine – read a line
2) The result is written into
1) Management is
the variable ‘result’
transferred to the console
[Link]
33
Operators
Operator priorities and the order of execution
Except assignment operators, all other operators are applied from left to right
Assignment operators and the operator ?: are applied from right to left
Use brackets
Some operators can be redefined
[Link]
34
Execution priority
Common Operators Example
• Equality == !=
• Comparison < > <= >= is
• Conditionals && || ?:
• Adding 1 ++
• Subtracting 1 --
• Arithmetic + - * / %
• Assignment operators = *= /= %= += -=
<<= >>= &= ^=
|=
[Link]
35
Assignment operators
Analog (expression from the
Operator
above example)
+= x = x + 1;
-= x = x - 1;
*= x = x*1;
/= x = x/1;
%= x = x%1;
|= x = x | 1;
^= x = x^1;
[Link]
36
Conditionals. Operator if
If the expression in brackets is true, execute the code block
void WriteLog(int severity,String msg)
{
String result="";
if (severity < 3)
{
result = "Error : ";
}
else if (severity < 5)
{
result = "Warn : ";
}
else
{
result = "Info : ";
}
[Link](result + msg);
[Link]
}
37
Operator switch:
[Link]
38
Loops
Types of loops
Early loop exit
Practice
[Link]
39
For loop
Using the for loop, you can once and again execute an operator or a
block of operators until a certain expression takes the value false.
for (initializer; condition; iterator)
body
[Link]
40
While loop
The while operator executes an operator or a block of operators until
a certain expression takes the value false.
[Link]
41
Do while loop
The construction do while guarantees that the loop body is executed
at least once, irrespective of any condition
[Link]
42
Instruction inside the loop
For early exit from the loop, use the key
word break;
For starting the next iteration, use the key
word continue;
[Link]
43
Practice
Arrange for continuous input of numbers from the keyboard until the
user enters 0. Once zero is entered, display on the screen the number
of positive numbers, that were entered, and negative numbers, and
the arithmetic average.
To convert the entered symbols into numbers, use the function [Link];
[Link]
44
Functions
Definition
Function signature
Function overloading
Passing arguments to the function
Perfect function
[Link]
45
Definition
Function is a fragment of program code (subprogram) which you can
address from another location in the program.
It’s a set of instructions that must perform one task!
This task defines the function name.
Example:
[Link]
46
Functions in С#
Since C# is a fully object-oriented language, all functions (except
anonymous) are methods (class functions)!
[Link]
47
Function signature
Signatures must be unique within a class
Forms Signature Doesn't form
Definition Signature definition
Method name Parameter name
Parameter types Returned value
Parameter modifiers
[Link]
48
Function overloading
Methods with the same name within a class
but with different parameters
class OverloadingExample
{
static int Add(int a, int b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static void Main()
{
[Link](Add(1, 2) + Add(1, 2, 3));
}
}
[Link]
49
Parameters with a default value
Supported by C# 4.0
No need for a large number of overloaded methods
Should be declared at the end of parameter list and known at the
time of compilation
[Link]
50
Perfect function
A perfect function works only with the arguments passed to it and
always returns the result of its work,
or informs the calling code that
it cannot perform its task -
generates exceptions (dies)
The Samurai Principle
[Link]
51
Passing arguments to the function
When arguments are passed to the function, variables (objects) of
the value type are copied (the function deals with a copy of
variable).
Reference types are not copies - the function deals with the
object that exists in the calling code.
[Link]
52
Passing arguments to the function
A value type can be passed by reference (without copying) using the
following two methods:
with the key words ref , in , out
with the help of boxing
[Link]
53
Passing arguments to the function
A variable that is passed as ref should be initialized before passing
it to the function and can be changed in the function.
A variable that is passed as in should be initialized before passing it
to the function and cannot be changed in the function.
A variable that is passed as out should be changed in the function.
[Link]
54
Passing arguments to the function
Value type by reference Value type by value
c2
[Link]
55
Passing arguments to the function
Using the key word params you can specify a parameter that
takes a variable number of arguments
Calling
[Link]
56
Demonstration of passing
various parameters
DEMO
[Link]
57
Practice
The keyboard is used to input 4 values:
Integers :
Height
Day of week
Line :
Gender
Name
This is the description of a child who comes to an amusement park.
[Link]
58
Practice (continued)
There are 3 attractions in the park:
Batman (open Mon, Wen, Fri; only for boys over 150 cm tall)
Swan (open Tue, Wen, Thu; for girls over 120 and below 140 cm
tall, and boys below 140 cm tall)
Pony (for all, open daily, except Sun)
If a child is allowed to the attraction, we invoke a function that
displays the child’s name and the name of attraction.
[Link]
59
Rules and Best Practices
Variables:
The local variable name in lowerncase
The variable name points to what kind of data is stored in it
(e.g. kidsName, age, openingTime, maximumHeightForEntrance)
Declare the variable just before using it
[Link]
60
Rules and Best Practices
Functions:
A function should have only one task
Normal size – 10 lines
The function name clearly indicates what it does and what it returns
(e.g. IsAttractionOpened)
DRY:
“Every piece of knowledge must have a single, unambiguous,
authoritative representation within a system.” Andrew Hunt, David
Thomas "The Pragmatic Programmer"
Don’t duplicate your code — take it out to functions
[Link]
61
Arrays
Definition
Practice
[Link]
62
Arrays
An array is an ordered collection of elements of the same data type.
It is accessed through the array name together with the offset of the required
element from the start of the array.
All elements are stored in the memory one after another.
The first element has the index ‘0’.
myNumbers[1]
int [] myNumbers = {365, 24, 12, 60, 30}
365 24 12 60 30
[Link]
63
Practice
Conditions of the previous task (see Attraction Evolution)
Task:
Change your code so that you can get a list (array) of all attractions which a
child can enjoy depending on the child’s characteristics (the access rules
remain unchanged).
In the previous version, the first suitable attraction was displayed, and now
you should display a list of suitable attractions.
[Link]
64
Arrays
In С# you can create multidimensional and jagged arrays. You should
study them if you go deeper to algorithms.
In real life (commercial projects), arrays are replaced by generic
collections that implement various data structures and numerous
predefined methods of dealing with them.
Generic collections will be discussed later in this course.
[Link]
65
Summary
Memory. Variables. Visibility Scope
Data Types
Arithmetical and logical operations
Conditionals
loops
Functions
Arrays
[Link]
66
Questions
[Link]