Mod 3
Mod 3
Module 3
Lesson 1
3. Overview: In this module we will get acquainted with the operators in C# and the 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.
4. Objectives:
Operators
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.
What Is an Operator?
After we have learned how to declare and set a variable in the previous module, we will discuss
how to perform various operations with them. For this purpose we will get familiar with
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.
Operators in C#
Operators in C# can be separated in several different categories: - Arithmetic operators – they are
used to perform simple mathematical operations.
Operators can be separated into different types according to the number of arguments they could
take:
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.
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.
Operators – Example
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.
Operator Precedence in C#
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.
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)
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.
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.
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.
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:
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
Laws of De Morgan Logical operations fall under the laws of De Morgan from the mathematical
logic:
The first law states that the negation of the conjunction (logical AND) of two propositions is equal
to the disjunction (logical OR) of their negations.
The second law states that the negation of the disjunction of both statements is equivalent to the
conjunction of their negations.
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.
Here is an example, which shows concatenations of two strings and a string with a number:
In the example we initialize two variables of type string and assign them values. On the third and
fourth row we concatenate both strings and pass the results to the method Console.WriteLine() to
print it on the console. On the next line we join the resulting string with a space and the number 5.
We assign the returned value to the variable csharpDotNet5, which will automatically be converted
to type string. On the last row we print the result.
Comparison Operators
Comparison operators in C# are used to compare two or more operands. C# supports the following
comparison operators:
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.
Assignment Operators
The operator for assigning value to a variable is "=" (the character for mathematical equation). The
syntax used for assigning value is as it follows:
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.
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:
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); // 5
Conversion to String
If it is necessary, we can convert any type of data, including the value null, to string. The
conversion of strings is done automatically whenever you use the concatenation operator (+) and
one of the arguments is not of type string. In this case the argument is converted to a string and the
operator returns a new string representing the concatenation of the two strings.
Another way to convert different objects to type string is to call the method ToString() of the
variable or the value. It is valid for all data types in .NET Framework. Even calling 3.ToString()
is fully valid in C# and the result will return the string "3".
Let’s take a look on several examples for converting different data types to
string:
int a = 5;
int b = 7;
string sum = "Sum = " + (a + b);
Console.WriteLine(sum);
string incorrect = "Sum = " + a + b;
Console.WriteLine(incorrect);
Console.WriteLine( "Perimeter = " + 2 * (a + b) + ". Area = " + (a * b) + ".");
From the results it is obvious, that concatenating a number to a character string returns in result
the string followed by the text representation of the number. Note that the "+" for concatenating
strings can cause unpleasant effects on the addition of numbers, because it has equal priority with
the operator "+" for mathematical addition. Unless the priorities of the operations are changed by
placing the brackets, they will always be executed from left to right.
Expressions
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 r = (150-20) / 2 + 5;
// Expression for calculating the surface of the circle
double surface = Math.PI * r * r;
// Expression 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
Exercises
Grading System
Output =50%
Mid-Term/Final Examination =25%
Quizzes =15%
Attendance =10%
100%
7. References
LORENA P. FLORITA
College Instructor
Noted:
MRS. ELVIE D. ARAGONES, PhD (cand.)
Program Chairperson
Approved by: