C# Programming Fundamentals at LSPU
C# Programming Fundamentals at LSPU
The online discussion will happen on November 1-26, 2021, from 9:30 -
11:30AM and/or 1:00OM – 4:00OM PST.
(For further instructions, refer to your Google Classroom and see the
schedule of activities for this module)
Offline Activities
(e-Learning/Self- Lecture Guide
Paced)
1. Data Types
that is used to classify text and an integer is a data type used to classify
whole numbers.
C# primitives are also called value types and predefined in the .NET
framework. Primitive types can be assigned a value directly. The value
assigned is stored on the stack as opposed to the heap.
A Stack is used for static memory allocation and Heap for dynamic memory
allocation, both stored in the computer's RAM. Variables allocated on the
stack are stored directly to the memory and access to this memory is very
fast, and its allocation is dealt with when the program is compiled.
While value types are stored generally in the stack, reference types are
stored in the managed heap. A value type derives from System.ValueType
and contains the data inside its own memory allocation. In other words,
variables or objects or value types have their own copy of the data.
Default
Type Represents Range Value
Bool Boolean value True or False False
Byte 8-bit unsigned integer 0 to 255 0
Char 16-bit Unicode character U +0000 to U +ffff ‘\0’
128-bit precise decimal
Decima (-7.9 x 1028 to 7.9 x 1028) / 100 to
values with 28-29 significant 28 0.0M
l
digits
64-bit double-precision
Double (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D
floating point type
32-bit single-precision
Float -3.4 x 1038 to + 3.4 x 1038 0.0F
floating point type
Int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
-923,372,036,854,775,808 to
Long 64-bit signed integer type 0L
9,223,372,036,854,775,807
Sbyte 8-bit signed integer type -128 to 127 0
Short 16-bit signed integer type -32,768 to 32,767 0
Uint 32-bit unsigned integer type 0 to 4,294,967,295 0
0 to
Ulong 64-bit unsigned integer type 0
18,446,744,073,709,551,615
Ushort 16-bit unsigned integer type 0 to 65,535 0
The reference types do not contain the actual data stored in a variable, but
they contain a reference to the variables.
5. Object Type
The Object Type is the ultimate base class for all data types in C# Common
Type System (CTS). The object types can be assigned values of any other
types, value types, reference types, predefined or user-defined types.
However, before assigning values, it needs type conversion.
WhenCertified
ISO 9001:2015 a value type is converted to object type, it is called boxing and on the
other hand, when an object type is converted to a value type, it is called
Level I Institutionally Accredited
unboxing.
Boxing Conversion
int i = 123;
object o = (object)i; // explicit boxing
Unboxing Conversion
6. Dynamic Type
You can store any type of value in the dynamic data type variable. Type
checking for these types of variables takes place at run-time.
Syntax for declaring a dynamic type is:
For example,
dynamic d = 20;
Dynamic types are similar to object types except that type checking for
ISO 9001:2015 Certified
object type variables takes place at compile time, whereas that for the
dynamic type variables takes place at run time.
Level I Institutionally Accredited
7. String Type
The String Type allows you to assign any string values to a variable. The
string type is an alias for the System.String class. It is derived from object
type. The value for a string type can be assigned using string literals in two
forms: quoted and @quoted.
For example,
@"Hello Universe";
8. Pointer Type
Pointer type variables store the memory address of another type. Pointers
in C# have the same capabilities as the pointers in C or C++.
type* identifier;
For example,
char* cptr;
int* iptr;
9. Variables
Each variable has a specific type, which determines the size and layout of
the variable's memory, the range of values that can be stored within that
memory, and the set of operations that can be applied to the variable.
Type Example
sbyte, byte, short, ushort, int, uint, long, ulong, and
Integral types
char
Floating point types float and double
Decimal types Decimal
Boolean types true or false values, as assigned
Nullable types Nullable data types
10.Defining Variables
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float,
double, or any user-defined data type, and variable_list may consist of one
or more identifier names separated by commas.
int i, j, k;
char c, ch;
float f, salary;
double d;
11.Variable Names
ISO 9001:2015 Certified
• The name can contain letters, digits, and the underscore character
(_).
• The first character of the name must be a letter. The underscore is
also a legal first character, but its use is not recommended at the
beginning of a name. An underscore is often used with special
commands, and it's sometimes hard to read.
• Case matters (that is, upper- and lowercase letters). C# is case-
sensitive; thus, the names count and Count refer to two different
variables.
• C# keywords can't be used as variable names. Recall that a keyword
is a word that is part of the C# language. (A complete list of the C#
keywords can be found in Appendix B, "C# Keywords.")
The following list contains some examples of valid and invalid C# variable
names:
Percent Legal
y2x5__w7h3 Legal
yearly_cost Legal
int i = 100;
12.Initializing Variables
Level I Institutionally Accredited
variable_name = value;
using System;
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following
result:
ISO 9001:2015 Certified
The simplest method to get input from the user is by using the ReadLine()
method of the Console class. However, Read() and ReadKey() are also
available for getting input from the user. They are also included in Console
class. Further discussions of Read() and ReadLine() will be discussed in
Module 7.
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
When the above code is compiled and executed, it produces the following
result:
Variables are lvalues and hence they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and hence they may not be
assigned and cannot appear on the left-hand side.
ISO 9001:2015 Certified
int g = 20;
10 = 20;
There are two (2) data types in C# and these are the value and reference
types.
Value types are stored in the program execution stack and directly contain
their value. Value types are the primitive numeric types, the character type
and the Boolean type: sbyte, byte, short, ushort, int, long, ulong, float,
double, decimal, char, bool. The memory allocated for them is released
when the program exits their range, i.e. when the block of code in which
they are defined completes its execution. For example, a variable declared
in the method Main() of the program is stored in the stack until the program
completes execution of this method, i.e. until it finishes (C# programs
terminate after fully executing the Main() method).
Reference types allocate dynamic memory for their creation. They also
release some dynamic memory for a memory cleaning (garbage
collector), when it is no longer used by the program. It is unknown exactly
when a given reference variable will be released of the garbage collector as
this depends on the memory load and other factors. Since the allocation and
program execution, their size might not be known in advance. For example,
Level I Institutionally Accredited
a variable of type string can contain text data which varies in length.
Actually, the string text value is stored in the dynamic memory and can
occupy a different volume (count of bytes) while the string variable stores
the address
of the text value.
Reference types are all classes, arrays and interfaces such as the types:
object, string, byte[]. We will learn about classes, objects, strings, arrays and
interfaces in the next chapters of this book. For now, it is enough to know
that all types, which are not value, are reference and their values are stored
in the heap (the dynamically allocated memory).
In this example we will illustrate how value and reference types are
represented in memory. Consider the execution of the following
programming code:
int i = 42;
char ch = 'A';
bool result = true;
object obj = 42;
string str = "Hello";
byte[] bytes = { 1, 2, 3 };
If we now execute the following code, which changes the values of the
variables, we will see what happens to the memory when changing the
value and reference types:
i = 0;
ch = 'B';
result = false;
obj = null;
str = "Bye";
bytes[1] = 0;
After these changes the variables and their values are located in the
memory as follows:
As you can see from the figure, a change in a value type (i = 0) changes its
value directly into the stack. When changing a reference type, things are
different: the value is changed in the heap (bytes[1] = 0). The variable
that keeps the array reference remains unchanged (0x00190D11). When
assigning a null value in a reference type, that reference is disconnected
from its value and the variable remains with no value (obj = null).
When assigning new value to an object (a reference type variable) the new
object is allocated in the heap (the dynamic memory) while the old object
remains free (unreferenced). The reference is redirected to the new object
(str = "Bye") while the old objects ("Hello") will be cleaned at some
moment by the garbage collector (the .NET Framework’s internal system
for
automatic memory cleaning) as they are not in use anymore.
17.Constants
Constants are immutable values which are known at compile time and do
not change for the life of the program. Constants are declared with the const
modifier. Only the C# built-in types (excluding System.Object) may be
declared as “const”
18.Literals
Primitive types, which we already met, are special data types built into the
C# language. Their values specified in the source code of the program are
called literals. One example will make this clearer:
ISO 9001:2015 Certified
In the above example, literals are true, 'C', 100, 20000 and 300000. They
are variable values set directly in the source code of the program.
19.Types of Literals
Boolean
Integer
Real
Character
String
Object literal null
20.Boolean Literals
21.Integer Literals
Integer literals are sequences of digits, a sign (+, -), suffixes and prefixes.
Using prefixes, we can present integers in the program source in decimal or
hexadecimal format. In the integer literals the following prefixes and
suffixes may take part:
- 'l' and 'L' as suffix indicates long type data, for example 357L.
- 'u' and 'U' as suffix indicates uint or ulong data type, for example
112u.
ISO 9001:2015 Certified
By default (if no suffix is used) the integer literals are of type int. Here are
Level I Institutionally Accredited
some examples of integer literals:
// This will cause an error, because the value 234L is not int
int longInt = 234L;
22.Real Literals
Real literals are a sequence of digits, a sign (+, -), suffixes and the decimal
point character. We use them for values of type float, double and decimal.
Real literals can be represented in exponential format. They also use the
following indications:
23.Character Literals
// An ordinary character
char character = 'a';
Console.WriteLine(character);
Console.WriteLine(character);
24.String Literals
String literals are used for data of type string. They are a sequence of
characters enclosed in double quotation marks.
All the escaping rules for the char type discussed above are also valid for
string literals.
I am at a new line.";
Console.WriteLine(verbatim);
// Console output:
// "Hello, Jude", he said.
// C:\Windows\Notepad.exe
25.Introduction
ISO 9001:2015 Certified
In this topic we will get acquainted with the operators in C# and the
Level I Institutionally Accredited
actions they can perform when used with the different data types. In the
beginning, we will explain which operators have higher priority and we will
analyze the different types of operators, according to the number of the
arguments they can take and the actions they perform. In the second part,
we will examine the conversion of data types. We will explain when and
why it is needed to be done and how to work with different data types.
26.What is an Operator?
Operators allow processing of primitive data types and objects. They take
as
an input one or more operands and return some value as a result. Operators
in C# are special characters (such as "+", ".", "^", etc.) and they perform
transformations on one, two or three operands. Examples of operators in
C#
are the signs for adding, subtracting, multiplication and division from math
(+, -, *, /) and the operations they perform on the integers and the real
numbers.
27.Operators in C#
- variables.
- Logical operators – operators that work with Boolean data types
and
ISO 9001:2015 Boolean expressions.
- Certified
- Binary operators – used to perform operations on the binary
Level I Institutionally Accredited
representation of numerical data.
- Type conversion operators – allow conversion of data from one
type to another.
28.Operator Categories
int a = 7 + 9;
Console.WriteLine(a); // 16
string firstName = "John";
string lastName = "Doe";
// Do not forget the space between them
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); // John Doe
The example shows how, as explained above, when the operator + is used
on
numbers it returns a numerical value, and when it is used on strings it
returns concatenated strings.
ISO 9001:2015 Certified
// Ambiguous
x + y / 100
// Unambiguous, recommended
x + (y / 100)
31.Arithmetic Operators
The arithmetical operators in C# +, -, * are the same like the ones in math.
They perform addition, subtraction and multiplication on numerical values
and the result is also a numerical value.
The division operator / has different effect on integer and real numbers.
When we divide an integer by an integer (like int, long and sbyte) the
returned value is an integer (no rounding, the fractional part is cut). Such
division is called an integer division. Example of integer division: 7 / 3 = 2.
ISO 9001:2015 Certified
When dividing two real numbers or two numbers, one of which is real (e.g.
float, double, etc.), a real division is done (not integer), and the result is a
real number with a whole and a fractional part. For example: 5.0 / 2 = 2.5.
In the division of real numbers, it is allowed to divide by 0.0 and
respectively the result is +∞ (Infinity), -∞ (-Infinity) or NaN (invalid
value).
The operator for increasing by one (increment) ++ adds one unit to the
value of the variable, respectively the operator -- (decrement) subtracts
one unit from the value. When we use the operators ++ and -- as a prefix
(when we place them immediately before the variable), the new value is
calculated first and then the result is returned. When we use the same
operators as post-fix (meaning when we place them immediately after the
variable) the original value of the operand is returned first, then the
addition or subtraction is performed.
int a = 5;
int b = 4;
Console.WriteLine(a + b); // 9
Console.WriteLine(a + (b++)); // 9
Console.WriteLine(a + b); // 10
Console.WriteLine(a + (++b)); // 11
Console.WriteLine(a + b); // 11
Console.WriteLine(14 / a); // 2
Console.WriteLine(14 % a); // 4
int one = 1;
int zero = 0;
// Console.WriteLine(one / zero); // DivideByZeroException
32.Logical Operators
The following example illustrates the usage of the logical operators and
their actions:
bool a = true;
bool b = false;
Console.WriteLine(a && b); // False
Console.WriteLine(a || b); // True
Console.WriteLine(!b); // True
Console.WriteLine(b || true); // True
Console.WriteLine((5 > 7) ^ (a == b)); // False
or more strings and returns the result as a new string. If at least one of the
arguments in the expression is of type string, and there are other operands
of type different from string, they will be automatically converted to type
string,
ISO 9001:2015 which allows successful string concatenation.
Certified
34.Bitwise Operators
Bitwise operators are very similar to the logical ones. In fact, we can
imagine that the logical and bitwise operators perform the same thing but
using different data types. Logical operators work with the values true and
false (Boolean values), while bitwise operators work with numerical values
and are applied bitwise over their binary representation, i.e., they work
with the bits of the number (the digits 0 and 1 of which it consists). Just like
the logical operators in C#, there are bitwise operators "AND" (&), bitwise
"OR" (|), bitwise negation (~) and excluding "OR" (^).
As we see bitwise and logical operators are very much alike. The difference
in theCertified
ISO 9001:2015 writing of "AND" and "OR" is that the logical operators are written
with
Level I Institutionally Accredited
double ampersand (&&) and double vertical bar (||), and the bitwise – with
a single ampersand or vertical bar (& and |). Bitwise and logical operators
for exclusive "OR" are the same "^". For logical negation we use "!", while
for bitwise negation (inversion) the "~" operator is used.
The bit shifting operators are used in the following way: on the left side of
the operator we place the variable (operand) with which we want to use the
operator, on the right side we put a numerical value, indicating how many
bits we want to offset. For example, 3 << 2 means that we want to move the
bits of the number three, twice to the left. The number 3 presented in bits
looks like this: "0000 0011". When you move twice left, the binary value
will look like this: "0000 1100", and this sequence of bits is the number 12.
If we look at the example, we can see that actually we have multiplied the
number by 4.
Bit shifting itself can be represented as multiplication (bitwise shifting left)
or division (bitwise shifting right) by a power of 2. This occurrence is due to
the nature of the binary numeral system. Example of moving to the right is
6 >> 2, which means to move the binary number "0000 0110" with two
positions to the right. This means that we will lose two right-most digits
and feed them with zeros on the left. The end result will be "0000 0001"
which is 1.
In the example we first create and initialize the values of two variables a
and
b. Then
ISO 9001:2015 we print on the console the results of some bitwise operations on
Certified
the
Level I Institutionally Accredited
two variables. The first operation that we apply is "OR". The example shows
that for all positions where there was 1 in the binary representation of the
variables a and b, there is also 1 in the result. The second operation is
"AND". The result of the operation contains 1 only in the right-most bit,
because the only place where a and b have 1 at the same time is their right-
most bit. Exclusive "OR" returns ones only in positions where a and b have
different values in their binary bits. Finally, the logical negation and bitwise
shifting: left and right, are illustrated.
All comparison operators in C# are binary (take two operands) and the
returned result is a Boolean value (true or false). Comparison operators
have lower priority than arithmetical operators but higher than the
assignment operators.
int x = 10, y = 5;
Console.WriteLine("x > y : " + (x > y)); // True
Console.WriteLine("x < y : " + (x < y)); // False
Console.WriteLine("x >= y : " + (x >= y)); // True
Console.WriteLine("x <= y : " + (x <= y)); // False
Console.WriteLine("x == y : " + (x == y)); // False
Console.WriteLine("x != y : " + (x != y)); // True
In the example, first we create two variables x and y and we assign them the
values 10 and 5. On the next line we print on the console using the method
Console.WriteLine(…) the result from comparing the two variables x and y
using the operator >. The returned value is true because x has a greater
value than y. Similarly, in the next rows the results from the other 5
comparison operators, used to compare the variables x and y, are printed.
ISO 9001:2015 Certified
36.Assignment Operators
Level I Institutionally Accredited
The operator for assigning value to a variable is "=" (the character for
mathematical equation). The syntax used for assigning value is as it follows:
int x = 6;
string helloString = "Hello string.";
int y = x;
Cascade Assignment
The assignment operator can be used in cascade (more than once in the
same expression). In this case assignments are carried out consecutively
from right to left. Here’s an example:
int x, y, z;
x = y = z = 25;
On the first line in the example we initialize three variables and on the
second
line we assign them the value 25.
int x = 2;
int y = 4;
x *= y; // Same as x = x * y;
Console.WriteLine(x); // 8
int x = 6;
int y = 4;
Console.WriteLine(y *= 2); // 8
int z = y = 3; // y=3 and z=3
Console.WriteLine(z); // 3
Console.WriteLine(x |= 1); // 7
Console.WriteLine(x += 3); // 10
Console.WriteLine(x /= 2); //
In the example, first we create the variables x and y and assign them values
6 and 4. On the next line we print on the console y, after we have assigned it
new value using the operator *= and the literal 2. The result of the
operation is 8. Further in the example we apply the other compound
assignment operators and print the result on the console.
37.Conditional Operator
The conditional operator (?:) uses the Boolean value of an expression to
determine which of two other expressions must be calculated and returned
as a result. The operator works on three operands and that is why it is
called ternary operator. The character "?" is placed between the first and
second operand, and ":" is placed between the second and third operand.
The first operand (or expression) must be Boolean, and the next two
operands
ISO 9001:2015 Certified must be of the same type, such as numbers or strings. The
It works like this: if operand1 is set to true, the operator returns as a result
operand2. Otherwise (if operand1 is set to false), the operator returns as
a
result operand3. The following example shows the usage of the operator
"?:":
int a = 6;
int b = 4;
Console.WriteLine(a > b ? "a>b" : "b<=a"); // a>b
Operator Description
"." The access operator "." (dot) is used to access the member
fields or methods of a class or object.
Example:
int[] arr = { 1, 2, 3 };
Console.WriteLine(arr[0]); // 1 38.Other Operators
string str = "Hello";
Console.WriteLine(str[1]); // e
() Brackets () are used to override the priority of execution of
expressions and operators. 39.Expressions
type cast The operator for type conversion (type) is used to convert
a variable from one type to another. Much of the program’s work
as The operator as also is used for type conversion but invalid is the calculation of
conversion returns null, not an exception. expressions. Expressions
new The new operator is used to create and initialize new are sequences of
objects. We will examine it in details in the Object Module. operators, literals and
is The is operator is used to check whether an object is variables that are
compatible with a given type (check object's type). calculated to a value of some
“??” The operator ?? is similar to the conditional operator ?:. The type (number, string, object
difference is that it is placed between two operands and or other type). Here are
returns the left operand only if its value is not null, some examples of
otherwise it returns the right operand. expressions:
Example:
int? a = 5;
Console.WriteLine(a
LSPU ?? -1);
SELF-PACED LEARNING MODULE: ITEC//
102:5FUNDAMENTALS OF PROGRAMMING
string name = null;
Console.WriteLine(name ?? "(no name)"); // (no
name)
Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna
int r = (150-20) / 2 + 5;
// Expression
ISO 9001:2015 Certified for calculating the surface of the circle
double surface = Math.PI * r * r;
Level I// Expression
Institutionally Accredited for calculating the perimeter of the circle
70
15393.80400259
439.822971502571
The calculation of the expression can have side effects, because the
expression can contain embedded assignment operators, can cause
increasing or decreasing of the value and calling methods. Here is an
example of such a side effect:
int a = 5;
int b = ++a;
Console.WriteLine(a); // 6
Console.WriteLine(b); // 6
When writing expressions, the data types and the behavior of the used
operators should be considered. Ignoring this can lead to unexpected
results. Here are some simple examples:
// First example
double d = 1 / 2;
Console.WriteLine(d); // 0, not 0.5
// Second example
double half = (double)1 / 2;
Console.WriteLine(half); // 0.5
In the first example, an expression divides two integers (written this way, 1
ISO 9001:2015 Certified
and two are integers) and assigns the result to a variable of type double.
Level I Institutionally Accredited
The result may be unexpected for some people, but that is because they are
ignoring the fact that in this case the operator "/" works over integers and
the result is an integer obtained by cutting the fractional part.
42.Division by Zero
int num = 1;
double denum = 0; // The value is 0.0 (real number)
int zeroInt = (int) denum; // The value is 0 (integer number)
Console.WriteLine(num / denum); // Infinity
Console.WriteLine(denum / denum); // NaN
Console.WriteLine(zeroInt / zeroInt); // DivideByZeroException
Engaging Activities
ISO 9001:2015 Certified
Please login to Google Class to see the complete instructions for the
Level I Institutionally Accredited
following engaging activities:
Performance Tasks
Please login to Google Class to see the complete instructions for the following performance tasks:
Learning Resources
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide
https://www.completecsharptutorial.com/csharp-articles
https://java2s.com/example/csharp/language-basics
https://www.tutorialspoint.com/csharp
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide
https://www.completecsharptutorial.com/csharp-articles
https://java2s.com/example/csharp/language-basics
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide
https://www.completecsharptutorial.com/csharp-articles
https://java2s.com/example/csharp/language-basics