Windows Programming with C#
Using Visual Studio IDE, Visual Basic .NET, Visual Studio Code + Mono
Windows Console Application
Instructor : Eyasu G.
Telegram : @JoshKiyakoo
Email : sendtokiya@gmail.com
Operators and Expressions
<date/time> <footer> 2
What Is an Operator?
In this section we will get acquainted with the operators in C# and the actions
they can perform when used with the different data types. Every
programming language uses operators, through which we can perform
different actions on the data.
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.
<date/time> <footer> 3
What Is an Operator? - Continued
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 variables.
- Logical Operators – operators that work with Boolean data types and Boolean
expressions.
- Increment | Decrement Operators – used to perform increase or decrease a value
of numerical data.
- Type Conversion Operators – allow conversion of data from one type to another.
- Binary operators – used to perform representation of numerical data.
<date/time> <footer> 4
Types of Operators by Number of Arguments
Operators can be separated into different types according to the
number of arguments they could take:
Operator Type Number of Arguments (Operands)
unary takes one operand
binary takes two operand
ternary takes three operand
All binary operators in C# are left-associative, i.e. the expressions
are calculated 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.
<date/time> <footer> 5
Operators in C#
Arithmetical 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 (for 2.3333).
Integer division by 0 is not allowed and causes a runtime exception
DivideByZeroException . The remainder of integer division of integers can be obtained
by the operator % .
For example, 7 % 3 = 1, and –10 % 2 = 0.
<date/time> <footer> 6
Operators in C# - Continued
Arithmetical Operators
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 OR Not A Number).
int iOne = 1;
int iZero = 0;
Error: Console.WriteLine ( iOne / iZero ); // DivideByZeroException
double dMinusOne = -1.0;
double dZero = 0.0;
Console.WriteLine ( dMinusOne / zero ); // -Infinity
Console.WriteLine ( iOne / dZero ); // Infinity
<date/time> <footer> 7
Operators in C#
Concatenation of String Operators
The operator + is used to join strings ( string ). It concatenates (joins) two 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 , which allows successful string concatenation.
Example:
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
<date/time> <footer> 8
Operators in C#
Comparison Operators
Comparison operators in C# are used to compare two or more operands. C# supports the
following comparison operators:
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)); // False Console.WriteLine("x != y : " + (x != y)); // True
Console.WriteLine("x >= y : " + (x >= y)); // False Console.WriteLine("x != y : " + (x != y)); // True
<date/time> <footer> 9
Operators in C#
Assignment Operators
The operator for assigning value to a variable is " = " (the character for mathematical
equation – equal sign).
The syntax used for assigning value is as it follows:
int xVal = 12;
string stringVal = "This is a string data.";
int yVal = xVal;
In the example we assign value 12 to the variable xVal. On the second line we assign a
text literal to the variable stringVal , and on the third line we copy the value of the
variable xVal to the variable yVal.
<date/time> <footer> 10
Operators in C#
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 must be of the same type, such as numbers or
strings.
int a = 9;
int b = 6;
Console.WriteLine ( (a > b) ? "a>b" : "b<=a"); // a>b
int iNum = ( a == b ) ? 1 : -1; // iNum will have value -1
<date/time> <footer> 11
Operators in C# - Continued
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” ( ! ).
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
false true true false true true
true false false false true true
false false true false false false
<date/time> <footer> 12
Operators in C#
Bitwise Operators
A bitwise operator is an operator that acts on the binary representation of numeric
types.
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
<date/time> <footer> 13
Operators in C#
Other Operators - The "." Operator
The access operator " . " (dot) is used to access the member fields or methods of a class or
object. Example of usage of point operator:
Console.WriteLine (DateTime.Now); // Prints the date + time
Other Operators - Square Brackets [] Operator
The Square brackets [] are used to access elements of an array by index, they are the so-
called indexer. Indexers are also used for accessing characters in a string.
int [] array = { 1, 2, 3 };
Console.WriteLine (array [0]); // 1
string stringVal = "MicroCSharp";
Console.WriteLine (stringVal [1]); // i
<date/time> <footer> 14
Operators in C#
Other Operators - The Operator "??"
The operator ?? is similar to the conditional operator ? : . The difference is that it is
placed between two operands and returns the left operand only if its value is not null,
otherwise it returns the right operand.
Example
Int a = 5;
Console.WriteLine (a ?? -1); // 5
string sName = null;
Console.WriteLine ( sName ?? "No Name"); // No Name
<date/time> <footer> 15
What is an Expression?
Much of the program’s work is the calculation of expressions. Expressions are sequences of
operators, literals and variables that are calculated to a value of some type (number,
string, object or other type). Here are some examples of expressions:
int someResult = (150 - 20) / 2 + 5;
// Expression for calculating the surface of the circle
double surfaceC = Math.PI * rad * rad;
// Expression for calculating the perimeter of the circle
double perimeterC = 2 * Math.PI * rad;
//Output Value
Console.WriteLine (someResult); 70
Console.WriteLine (surfaceC); 15393.80400259
Console.WriteLine (perimeterC); 439.822971502571
<date/time> <footer> 16
Expressions in C#
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
<date/time> <footer> 17
Expressions in C#
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 dVal = 1 / 2;
Console.WriteLine (dVal); // 0, but not 0.5
// Second example
double dHalf = (double) 1 / 2;
Console.WriteLine (dHalf); // 0.5, but not 0
<date/time> <footer> 18
Expressions in C#
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 iNum = 1;
double dNum = 0; // The value is 0.0 (real number)
int iZero = (int) dNum; // The value is 0 (integer number)
Console.WriteLine (iNum / dNum); // Infinity
Console.WriteLine (dNum / dNum); // NaN
Console.WriteLine (iZero / iZero); // DivideByZeroException
<date/time> <footer> 19
Expressions in C#
Use Brackets to Make Your Code Clear and Readable
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
<date/time> <footer> 20
Assignment 3
Write a program that takes as input a four-digit number in
format wxyz (e.g. 2021) and performs the following actions:
- Calculates the sum of the digits (in this example 2+0+2+1 = 5).
- Prints on the console the number in reversed order: zyxw (in
our example 1202).
- Puts the last digit in the first position: zwxy (in our example
1202).
- Exchanges the second and the third digits: wyxz (in this
example 2201).
<date/time> <footer> 21
Conditional Statements
<date/time> <footer> 22
Thank You !!!
<date/time> <footer> 23