0% found this document useful (0 votes)
445 views33 pages

C# Programming Fundamentals at LSPU

The document is a learning module from Laguna State Polytechnic University that discusses fundamentals of C# programming. It covers topics like data types in C#, primitive and non-primitive data types, value types and reference types, and operators. The module provides lecture content on these topics and assigns learning guide questions for students to answer related to C# programming concepts. It also lists online and offline activities for students to complete, including an online discussion and self-paced learning exercises.

Uploaded by

Carman Palma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
445 views33 pages

C# Programming Fundamentals at LSPU

The document is a learning module from Laguna State Polytechnic University that discusses fundamentals of C# programming. It covers topics like data types in C#, primitive and non-primitive data types, value types and reference types, and operators. The module provides lecture content on these topics and assigns learning guide questions for students to answer related to C# programming concepts. It also lists online and offline activities for students to complete, including an online discussion and self-paced learning exercises.

Uploaded by

Carman Palma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Republic of the Philippines

Laguna State Polytechnic University


Province of Laguna

LSPU Self-Paced Learning Module (SLM)


ISO 9001:2015 Certified

Level I Institutionally Accredited


Learning Outcomes

Student Learning Strategies

Online Activities A. Online Discussion via Google Meet


(Synchronous/ You will be directed to attend in a Two-Hour class discussion on Module
2. To have access to the Online Discussion, refer to this link:
Asynchronous) ____________________.

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)

B. Learning Guide Questions:


1. What is C# Programming Language?
2. What are the choices for installation of C# IDE for personal computers
and mobile devices?
3. How these IDEs and/or application performs personal computers and
mobile devices?
4. What are the difference types of literals in C#?
5. What are the value and reference types?
6. How the concepts of value and reference are important in the creation
of C# codes?
7. What are operators in C#?
8. What are the purpose and group of operators used in C#?
9. How the operator precedence performs in C#?

Offline Activities
(e-Learning/Self- Lecture Guide
Paced)
1. Data Types

A Data Type is a classification that specifies which type of value a variable


has and what type of mathematical, relational or logical operations can be
applied to it without causing an error. For example, a string is a data type

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

that is used to classify text and an integer is a data type used to classify
whole numbers.

ISO 9001:2015 Certified

2. Primitive and Non-primitive


Level I Institutionally Accredited

C# is a strongly typed language which means that variables must be


explicitly defined. The compiler will throw an error if a value assigned or
being assigned is not the data type specified. An example of this is a variable
assigned a number cannot hold text later on in the program. Also, a variable
defined as an integer cannot be assigned a string.

3. Primitive (Value Type)

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.

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

ISO 9001:2015 Certified

Level I Institutionally Accredited

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.

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

ISO 9001:2015 Certified

List of Available Value Types in C# 2010


Level I Institutionally Accredited

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

4. Non-primitive (Reference Type)

The reference types do not contain the actual data stored in a variable, but
they contain a reference to the variables.

In other words, they refer to a memory location. Using multiple variables,


the reference types can refer to a memory location. If the data in the
memory location is changed by one of the variables, the other variable
automatically reflects this change in value.

5. Object Type

The Object Type is the ultimate base class for all data types in C# Common

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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

It is also possible to perform the boxing explicitly as in the following


example, but explicit boxing is never required:

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:

dynamic <variable_name> = value;

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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,

String str = "Hello Universe";

A @quoted string literal looks as follows:

@"Hello Universe";

The user-defined reference types are: class, interface, or delegate. We will


discuss these types in Module 15.

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++.

Syntax for declaring a pointer type is:

type* identifier;

For example,

char* cptr;
int* iptr;

9. Variables

Variables are used to store information to be referenced and used inside a


program.

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

ISO 9001:2015 Certified

Level I Institutionally Accredited

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

Syntax for variable definition in C# is:

<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.

Below are some valid variable definitions:

int i, j, k;
char c, ch;
float f, salary;
double d;

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

11.Variable Names
ISO 9001:2015 Certified

Level I Institutionally Accredited


To use variables in your C# programs, you must know how to create
variable names. In C#, variable names must adhere to the following rules:

• 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:

Variable Name Legality

Percent Legal

y2x5__w7h3 Legal

yearly_cost Legal

_2010_tax Legal, but not advised

checking#account Illegal; contains the illegal character #

Double Illegal; is a C keyword

9byte Illegal; first character is a digit

You can initialize a variable at the time of definition as:

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

int i = 100;

ISO 9001:2015 Certified

12.Initializing Variables
Level I Institutionally Accredited

Variables are initialized (assigned a value) with an equal sign followed by a


constant expression. The general form of initialization is:

variable_name = value;

Variables can be initialized in their declaration. The initializer consists of an


equal sign followed by a constant expression as:

<data_type> <variable_name> = value;

Here are examples:

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

It is a good programming practice to initialize variables properly, otherwise


sometimes program may produce unexpected result.

The following example uses various types of variables:

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(); 
        }
    }
}

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

When the above code is compiled and executed, it produces the following
result:
ISO 9001:2015 Certified

Level I Institutionally Accredited


a = 10, b = 20, c = 30

13.Accepting Value from User

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.

The difference between ReadLine(), Read() and ReadKey() method is:


 ReadLine(): The ReadLine() method reads the next line of input
from the standard input stream. It returns the same string.
 Read(): The Read() method reads the next character from the
standard input stream. It returns the ascii value of the character.
 ReadKey(): The ReadKey() method obtains the next key pressed
by user. This method is usually used to hold the screen until user
press a key.

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:

Enter a string – C# Programming


You entered C# Programming

14.Lvalue and Rvalue in C#

There are two kinds of expressions in C#:

1. lvalue: An expression that is an lvalue may appear as either the


left-hand or right-hand side of an assignment.
2. rvalue: An expression that is an rvalue may appear on the right-
but not left-hand side of an assignment.

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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

Level I Institutionally Accredited


Following is a valid C# statement:

int g = 20;

But following is not a valid statement and would generate compile-time


error:

10 = 20;

15.Value and Reference Types

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 keep a reference (address), in the program execution


stack, and that reference points to the dynamic memory (heap), where
their value is stored. The reference is a pointer (address of the memory
cell) indicating the actual location of the value in the heap. An example of a
value
at address in the stack for execution is 0x00AD4934. The reference has a
type. The reference can only point to objects of the same type, i.e. it is a
strongly typed pointer. All reference types can hold a null value. This is a
special service value, which means that there is no value.

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

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

release of memory is a slow operation, it can be said that the reference


types are slower than the value ones.

As reference data types are allocated and released dynamically during


ISO 9001:2015 Certified

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).

16.Value and Reference Types and the 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 };

At this point the variables are located in the memory as follows:

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

ISO 9001:2015 Certified

Level I Institutionally Accredited

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:

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

ISO 9001:2015 Certified

Level I Institutionally Accredited

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

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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

bool result = true;


Level I Institutionally Accredited
char capitalC = 'C';
byte b = 100;
short s = 20000;
int i = 300000;

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

There are several types of literals in C# language and these are:

 Boolean
 Integer
 Real
 Character
 String
 Object literal null

20.Boolean Literals

Boolean literals are either true or false. When we assign a value to a


variable of type bool we can use only one of these two values or a Boolean
expression (which is calculated to true or false).

Here is an example of a declaration of a variable of type bool and assigning


a
value, which represents the Boolean literal true:

bool result = true;

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:

- "0x" and "0X" as prefix indicates hexadecimal values, for example


0xA8F1;

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

- '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:

// The following variables are initialized with the same value


int numberInDec = 16;
int numberInHex = 0x10;

// 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:

-'f' and 'F' as suffixes mean data of type float;


-'d' and 'D' as suffixes mean data of type double;
-'m' and 'm' as suffixes mean data of type decimal;
-'e' is an exponent, for example, "e-5" means the integer part
multiplied by 10-5.
By default (if there is no suffix), the real numbers are of type double. Here
are some examples of real literals' usage:

// The following is the correct way of assigning a value:


float realNumber = 12.5f;

// The following causes an error, because 12.5 is double


float realNumber = 12.5;

23.Character Literals

Character literals are single characters enclosed in apostrophes (single


quotes). We use them to set the values of type char. The value of a character
literal can be:

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

- a character, for example 'A';


- a character code, for example '\u0065';
- Certified
ISO 9001:2015 an escaping sequence;
Level I Institutionally Accredited
Escaping Sequences

Sometimes it is necessary to work with characters that are not displayed on


the keyboard or with characters that have special meanings, such as the
“new line” character. They cannot be represented directly in the source
code of the program and in order to use them we need special techniques,
which we will discuss now.

Escaping sequences are literals. They are a sequence of special characters,


which describe a character that cannot be written directly in the source
code. This is, for instance, the “new line” character.

There are many examples of characters that cannot be represented directly


in the source code: a double quotation mark, tab, new line, backslash and
others. Here are some of the most frequently used escaping sequences:

- \' – single quote


- \" – double quotes
- \\ – backslash
- \n – new line
- \t – offset (tab)
- \uXXXX – char specified by its Unicode number, for example \u03A7.

The character \ (backslash) is also called an escaping character because it


allows the display on screen (or other output device) of characters that
have special meaning or effect and cannot be represented directly in the
source code. Here are some examples of character literals and escaping
sequences:

// An ordinary character
char character = 'a';
Console.WriteLine(character);

// Unicode character code in a hexadecimal format


character = '\u003A';
Console.WriteLine(character);

// Assigning the single quotiation character (escaped as \')


character = '\'';

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

Console.WriteLine(character);

// Assigning the backslash character (escaped as \\)


character
ISO 9001:2015 Certified = '\\';
Console.WriteLine(character);
Level I Institutionally Accredited
// Console output:
// a
// :
// '
// \

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.

Strings can be preceded by the @ character that specifies a quoted string


(verbatim string). In quoted strings the rules for escaping are not valid, i.e.
the character \ means \ and is not an escaping character. Only one
character needs to be escaped in the quoted strings – the character "
(double-quotes) and it is escaped in the following way – by repeating it ""
(double doublequotes). All other characters are treated literally, even the
new line.Quoted strings are often used for the file system paths naming.
Here are few examples for string literals usage:

string quotation = "\"Hello, Jude\", he said.";


Console.WriteLine(quotation);
string path = "C:\\Windows\\Notepad.exe";
Console.WriteLine(path);
string verbatim = @"The \ is not escaped as \\.

I am at a new line.";
Console.WriteLine(verbatim);
// Console output:
// "Hello, Jude", he said.
// C:\Windows\Notepad.exe

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

// The \ is not escaped as \\.


// I am at a new line.

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.

Every programming language uses operators, through which we can


perform different actions on the data. Let’s take a look at the operators in
C# and see what they are for and how they are used.

26.What is an Operator?

An operator is a symbol that tells the compiler to perform specific


mathematical or logical manipulations. C# has rich set of built-in operators
and provides different type of operators.

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#

Operators in C# can be separated in several different categories

- Arithmetic operators – they are used to perform simple


mathematical operations.
- Assignment operators – allow assigning values to variables.
- Comparison operators – allow comparison of two literals and/or

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

- 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

Category Operators 29.Types of Operators by


arithmetic -, +, *, /, %, ++, -- Number of Arguments
Logical &&, ||, !, ^
Binary &, |, ^, ~, <<, >> Operators can be separated
comparison (or relational) ==,!=, >, <, >=, <= into different types
assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, according to the number of
>>= arguments they could have:
string concatenation +
Operator type (or type cast)
type conversion (type), as
Number of, arguments
is, typeof, (operand)
sizeof All binary operators in C# are
Unary
other (or miscellaneous) ., new, one
takes (), [] , ?:operand
(1) , ?? left-associative, i.e. the
Binary takes two (2) operands expressions are calculated
ternary takes three (3) operands from left to right, except for the
assignment operators. All assignment operators and conditional operators ?:
and ?? are right associative, i.e. the expressions are calculated from right to left.
The unary
operators are not associative.

Some of the operators in C# perform different operations on the different


data types. For example, the operator +. When it is used on numeric data
types (int, long, float, etc.), the operator performs mathematical addition.
However, when we use it on strings, the operator concatenates (joins
together) the content of the two variables/literals and returns the new
string. Here is an example of using operators:

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

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

on
numbers it returns a numerical value, and when it is used on strings it
returns concatenated strings.
ISO 9001:2015 Certified

30. Operator Precedence in C#


Level I Institutionally Accredited

Some operators have precedence (priority) over others. For example, in


math multiplication has precedence over addition. The operators with a
higher precedence are calculated before those with lower. The operator ()
is used to change the precedence and like in math, it is calculated first.

The following table illustrates the precedence of the operators in C#:

Priority Operators The operators located upper


Highest priority (, ) in the table have higher
++, -- (as postfix), new, (type), typeof, sizeof precedence than those below
++, -- (as prefix), +, - (unary), !, ~ them, and respectively they
*, /, % have an advantage in the
… + (string concatenation)
calculation of an expression.
+, -
To change the precedence of
<<, >>
<, >, <=, >=, is, as
an operator we can use
==, != brackets.
&, ^, |
Lowest priority && When we write expressions
|| that are more complex or
… ?:, ?? have many operators, it is
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= recommended to use
brackets to avoid
difficulties in reading and understanding the code. For example:

// 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.

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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

Integer division by 0 is not allowed and causes a runtime exception


Level I Institutionally Accredited
DivideByZeroException. The remainder of integer division of integers can
be obtained by the operator %. For example, 7 % 3 = 1, and –10 % 2 = 0.

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.

Here are some examples of arithmetic operators and their effect:

int squarePerimeter = 17;


double squareSide = squarePerimeter / 4.0;
double squareArea = squareSide * squareSide;
Console.WriteLine(squareSide); // 4.25
Console.WriteLine(squareArea); // 18.0625

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

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

double dMinusOne = -1.0;


double dZero = 0.0;
Console.WriteLine(dMinusOne / zero); // -Infinity
Console.WriteLine(one
ISO 9001:2015 Certified / dZero); // Infinity

Level I Institutionally Accredited

32.Logical Operators

Logical (Boolean) operators take Boolean values and return a Boolean


result (true or false). The basic Boolean operators are "AND" (&&), "OR"
(||), "exclusive OR" (^) and logical negation (NOT) (!). The following table
contains the logical operators in C# and the operations
that they perform:
x y !x x && y x || y x^y
true true false true true false
true false false false true true
false true true false true true
false false true false false false
The table and the following example show that the logical "AND" (&&)
returns true only when both variables contain truth. Logical "OR" (||)
returns true when at least one of the operands is true. The logical negation
operator (!) changes the value of the argument. For example, if the operand
has a value
true and a negation operator is applied, the new value will be false. The
negation operator is a unary operator and it is placed before the argument.
Exclusive "OR" (^) returns true if only one of the two operands has the
value
true. If the two operands have different values, exclusive "OR" will return
the result true, if they have the same values it will return false.

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

33.String Concatenation Operator

The operator + is used to join strings (string). It concatenates (joins) two

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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

Level I Institutionally Accredited


Here is an example, which shows concatenations of two strings and a string
with a number:

string csharp = "C#";


string dotnet = ".NET";
string csharpDotNet = csharp + dotnet;
Console.WriteLine(csharpDotNet); // C#.NET
string csharpDotNet4 = csharpDotNet + " " + 5;
Console.WriteLine(csharpDotNet4); // C#.NET 5

34.Bitwise Operators

A bitwise operator is an operator that acts on the binary representation of


numeric types. In computers all the data and particularly numerical data is
represented as a series of ones and zeros. The binary numeral system is
used for this purpose. For example, number 55 in the binary numeral
system is represented as 00110111.

Binary representation of data is convenient because zero and one in


electronics can be implemented by Boolean circuits, in which zero is
represented as "no electricity" or for example with a voltage of -5V and the
one is presented as "have electricity" or say with voltage +5V.

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" (^).

Bitwise Operators and their Performance

The bitwise operators' performance on binary digits 0 and 1 is shown in the


following table:
x y ~x x&y x|y x^y
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING
Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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.

In programming there are two bitwise operators that have no analogue in


logical operators. These are the bit shift left (<<) and bit shift right (>>).
Used on numerical values, they move all the bits of the value to the left or
right. The bits that fall outside the number are lost and replaced with 0.

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.

Here is an example of using bitwise operators. The binary representation of


the numbers and the results of the bitwise operators are shown in the
comments (green text):

byte a = 3; // 0000 0011 = 3


byte b = 5; // 0000 0101 = 5
Console.WriteLine(a | b); // 0000 0111 = 7
Console.WriteLine(a & b); // 0000 0001 = 1
Console.WriteLine(a ^ b); // 0000 0110 = 6
Console.WriteLine(~a & b); // 0000 0100 = 4
Console.WriteLine(a << 1); // 0000 0110 = 6
Console.WriteLine(a << 2); // 0000 1100 = 12
Console.WriteLine(a >> 1); // 0000 0001 = 1

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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.

35.Comparison (or relational) Operators

Comparison operators in C# are used to compare two or more operands. C#


supports the following comparison operators:

- greater than (>)


- less than (<)
- greater than or equal to (>=)
- less than or equal to (<=)
- equality (==)
- difference (!=)

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.

The following example demonstrates the usage of comparison operators in


C#:

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

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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:

operand1 = literal, expression or operand2;

Here is an example to show the usage of the assignment operator:

int x = 6;
string helloString = "Hello string.";
int y = x;

In the example we assign value 6 to the variable x. On the second line we


assign a text literal to the variable helloString, and on the third line we
copy the value of the variable x to the variable y.

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.

Compound Assignment Operators


Except the assignment operator there are also compound assignment
operators. They help to reduce the volume of the code by typing two
operations together with an operator: operation and assignment.
Compound operators have the following syntax:

operand1 operator = operand2;

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

The upper expression is like the following:

operand1 = operand1 operator operand2;


ISO 9001:2015 Certified
Here is an example of a compound operator for assignment:
Level I Institutionally Accredited

int x = 2;
int y = 4;

x *= y; // Same as x = x * y;
Console.WriteLine(x); // 8

The most commonly used compound assignment operators are += (adds


value of operand2 to operand1), -= (subtracts the value of the right
operand from the value of the left one). Other compound assignment
operators are *=, /= and %=. The following example gives a good idea of
how the compound assignment
operators work:

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

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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

operator ?: has the following syntax:


Level I Institutionally Accredited

operand1 ? operand2 : operand3

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

double perimeter = 2 * Math.PI * r;


Console.WriteLine(r);
Console.WriteLine(surface);
Console.WriteLine(perimeter);

In the example three expressions are defined. The first expression


calculates
the radius of a circle. The second calculates the area of a circle, and the last
one finds the perimeter. Here is the result from the fragment above:

70
15393.80400259
439.822971502571

40.Side Effects of Expressions

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

41.Expressions, Data Types and Operator Priorities

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;

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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.

The second example shows that if we want to do division with fractions in


the result, it is necessary to convert to float or double at least one of the
operands. In this scenario the division is no longer integer and the result is
correct.

42.Division by Zero

Another interesting example is division by 0. Most programmers think that


division by 0 is an invalid operation and causes an error at runtime
(exception) but this is actually true only for integer division by 0. Here is an
example, which shows that fractional division by 0 is Infinity or NaN:

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

43.Using Brackets to Make the Code Clear

When working with expressions it is important to use brackets whenever


there is the slightest doubt about the priorities of the operations. Here is an
example that shows how useful the brackets are:

double incorrect = (double)((1 + 2) / 4);


Console.WriteLine(incorrect); // 0

double correct = ((double)(1 + 2)) / 4;


Console.WriteLine(correct); // 0.75

Console.WriteLine("2 + 3 = " + 2 + 3); // 2 + 3 = 23


Console.WriteLine("2 + 3 = " + (2 + 3)); // 2 + 3 = 5

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

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:

a. EA04 - Assign Age Display Program

b. EA05 - Input and Display Name Program

c. EA06 - Variable Assignments and Display program

d. EA07 - Required Screen Output 1

e. EA08 - Required Screen Output 2

f. EA09 - Swapping Program

g. EA10 - Largest and Smallest Number Program

h. EA11 - Sum, Squares, and Cubes Program

i. EA12 - The Same Signs Program

j. EA13 - Celsius to Fahrenheit Program

Performance Tasks
Please login to Google Class to see the complete instructions for the following performance tasks:

a. PT04 - Data Types and Variables

b. PT05 - Value and Reference Types and Literals

c. PT06 - Descriptive Statistics Program

d. PT07 - Operators and Expressions

e. PT08 - Digit Extraction Program

f. PT09 - Input and Output Statements

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING


Republic of the Philippines
Laguna State Polytechnic University
Province of Laguna

Understanding Directed Assessment


ISO 9001:2015 Certified
Please login to Google Class to see the complete instructions for the following performance
tasks: Level I Institutionally Accredited

UDA04 - User Information Input and Display Program 1

UDA05 - User Information Input and Display Program 2

UDA06 - Sample Student Grade’s Computation

UDA06 - Sample Calculator Program

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

LSPU SELF-PACED LEARNING MODULE: ITEC 102: FUNDAMENTALS OF PROGRAMMING

You might also like