0% found this document useful (0 votes)
45 views

C# Lab 2 C# Operators

Uploaded by

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

C# Lab 2 C# Operators

Uploaded by

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

Windows programming

C# lab 2
C# Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;

Although the + operator is often used to add together two values, like in the example above, it can
also be used to add together a variable and a value, or a variable and another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:

Operator Name Description Example


+ Addition Adds together two values x+y
- Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
/ Division Divides one value by another x/y
% Modulus Returns the division remainder x%y
++ Increment Increases the value of a variable by 1 x++
-- Decrement Decreases the value of a variable by 1 x--

C# Assignment Operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:

Page 1 of 9
Windows programming

Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;
x += 5;

A list of all assignment operators:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

C# Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example


== Equal to x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Page 2 of 9
Windows programming

C# Logical Operators
Logical operators are used to determine the logic between variables or values:

Operator Name Description Example


&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true

The C# Math class has many methods that allows you to perform mathematical tasks on
numbers.

Math.Max(x,y)
The Math.Max(x,y) method can be used to find the highest value of x and y:

C# Math
Example
Math.Max(5, 10);

Math.Min(x,y)
The Math.Min(x,y) method can be used to find the lowest value of of x and y:

Example
Math.Min(5, 10);

Math.Sqrt(x)
The Math.Sqrt(x) method returns the square root of x:

Example
Math.Sqrt(64);

Page 3 of 9
Windows programming

Math.Abs(x)
The Math.Abs(x) method returns the absolute (positive) value of x:

Example
Math.Abs(-4.7);

Math.Round()
Math.Round() rounds a number to the nearest whole number:

Example
Math.Round(9.99);

C# Strings
Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type string and assign it a value:

string greeting = "Hello";

String Length
A string in C# is actually an object, which contain properties and methods that can perform certain
operations on strings. For example, the length of a string can be found with the Length property:

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("The length of the txt string is: " + txt.Length);

Other Methods
There are many string methods available, for example ToUpper() and ToLower(), which returns
a copy of the string converted to uppercase or lowercase:

Page 4 of 9
Windows programming

Example
string txt = "Hello World";
Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD"
Console.WriteLine(txt.ToLower()); // Outputs "hello world"

String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:

Example
string firstName = "John ";
string lastName = "Doe";
string name = firstName + lastName;
Console.WriteLine(name);

Note that we have added a space after "John" to create a space between firstName and lastName
on print.

You can also use the string.Concat() method to concatenate two strings:

Example
string firstName = "John ";
string lastName = "Doe";
string name = string.Concat(firstName, lastName);
Console.WriteLine(name);

String Interpolation
Another option of string concatenation, is string interpolation, which substitutes values of
variables into placeholders in a string. Note that you do not have to worry about spaces, like with
concatenation:

Example
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";
Console.WriteLine(name);

Also note that you have to use the dollar sign ($) when using the string interpolation method.

String interpolation was introduced in C# version 6.

Page 5 of 9
Windows programming

Access Strings
You can access the characters in a string by referring to its index number inside square brackets
[].

This example prints the first character in myString:

Example
string myString = "Hello";
Console.WriteLine(myString[0]); // Outputs "H"

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

This example prints the second character (1) in myString:

Example
string myString = "Hello";
Console.WriteLine(myString[1]); // Outputs "e"

You can also find the index position of a specific character in a string, by using the IndexOf()
method:

Example
string myString = "Hello";
Console.WriteLine(myString.IndexOf("e")); // Outputs "1"

Another useful method is Substring(), which extracts the characters from a string, starting
from the specified character position/index, and returns a new string. This method is often used
together with IndexOf() to get the specific character position:

Example
// Full name
string name = "John Doe";

// Location of the letter D


int charPos = name.IndexOf("D");

// Get last name


string lastName = name.Substring(charPos);

// Print the result


Console.WriteLine(lastName);

Page 6 of 9
Windows programming

Special Characters
Because strings must be written within quotes, C# will misunderstand this string, and generate an
error:

string txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Escape character Result Description


\' ' Single quote
\" " Double quote
\\ \ Backslash

The sequence \" inserts a double quote in a string:

Example

string txt = "We are the so-called \"Vikings\" from the north.";

The sequence \' inserts a single quote in a string:

Example

string txt = "It\'s alright.";

The sequence \\ inserts a single backslash in a string:

Example

string txt = "The character \\ is called backslash.";

Other useful escape characters in C# are:

Code Result
\n New Line
\t Tab
\b Backspace

Page 7 of 9
Windows programming

Adding Numbers and Strings


WARNING!

C# uses the + operator for both addition and concatenation.

Remember: Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)

If you add two strings, the result will be a string concatenation:

Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

C# Booleans
Very often, in programming, you will need a data type that can only have one of two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, C# has a bool data type, which can take the values true or false.

Boolean Values
A boolean type is declared with the bool keyword and can only take the values true or false:

bool isCSharpFun = true;


bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False

Page 8 of 9
Windows programming

However, it is more common to return boolean values from boolean expressions, for conditional
testing (see below).

Boolean Expression
A Boolean expression is a C# expression that returns a Boolean value: True or False.

You can use a comparison operator, such as the greater than (>) operator to find out if an
expression (or a variable) is true:

Example
int x = 10;
int y = 9;
Console.WriteLine(x > y); // returns True, because 10 is higher than 9

Or even easier:

Example
Console.WriteLine(10 > 9); // returns True, because 10 is higher than 9

In the examples below, we use the equal to (==) operator to evaluate an expression:

Example
int x = 10;
Console.WriteLine(x == 10); // returns True, because the value of x is equal
to 10

Example
Console.WriteLine(10 == 15); // returns False, because 10 is not equal to 15

The boolean value of an expression is the basis for all C# comparisons and conditions.

You will learn more about conditions in the next section.

Page 9 of 9

You might also like