Professional Documents
Culture Documents
Application
What is C#?
ª C# is pronounced "C-Sharp".
ª It is an object-oriented programming language created by Microsoft that runs on the
.NET Framework.
ª C# has roots from the C family, and the language is close to other popular languages
like C++ and Java.
C# is used for:
Web applications VR
C# Syntax
We created a C# file called Program.cs, and we used the following code to print "Hello World"
to the screen:
BY:Moti B:
C# Lab Manual Console
Application
Example explained
Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more
readable.
Line 3: namespace is a used to organize your code, and it is a container for classes and other
namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to your program.
Every line of code that runs in C# must be inside a class. In our example, we named the class
Program.
Line 7: Another thing that always appear in a C# program, is the Main method. Any code inside
its curly brackets {} will be executed. You don't have to understand the keywords before and
after Main. You will get to know them bit by bit while reading this tutorial.
BY:Moti B:
C# Lab Manual Console
Application
Line 9: Console is a class of the System namespace, which has a WriteLine () method that is
used to output/print text. In our example it will output "Hello World!".
WriteLine or Write
The most common method to output something in C# is WriteLine(), but you can also
use Write().The difference is that WriteLine() prints the output on a new line each time,
while Write() prints on the same line (note that you should remember to add spaces when
needed, for better readability):
C# Comments
Comments can be used to explain C# code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. Single-line comments start with two forward
slashes (//).Any text between // and the end of the line is ignored by C# (will not be executed).
BY:Moti B:
C# Lab Manual Console
Application
This example uses a single-line comment before a line of code:
// This is a comment
Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored
by C#.
This example uses a multi-line comment (a comment block) to explain the code:
/* The code below will print the words Hello World to the screen, and it is amazing */
C# Variables
In C#, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
To create a variable, you must specify the type and assign it a value:
BY:Moti B:
C# Lab Manual Console
Application
Example: Create a variable called name of type string and assign it the value "Besufikad":
Console.Writeln(name);
You can also declare a variable without assigning the value, and assign the value later:
Example:
int myNum;
myNum = 25;
Console.Writeln(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Console.Writeln(myNum);
Constants
However, you can add the const keyword if you don't want others (or yourself) to overwrite
existing values (this will declare the variable as "constant", which means unchangeable and read-
only): Example:
BY:Moti B:
C# Lab Manual Console
Application
The const kewoard is useful when you want a variable to always store the same value, so that
others won’t mess up your code.an example that is often refered to as a constant,is PI(3.14159…)
Note:You cannot declare a constant variable without assigning the value.If you do,an error will
occur.a const field requires a value to be provided.
You can also use the + character to add a variable to another variable: see the following example:
Console.Writeln(fullname);
C# Identifiers
All C# variables must be identified with unique names.These unique names are
called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Example: //Good
int m = 60;
BY:Moti B:
C# Lab Manual Console
Application
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain whitespace
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or double) cannot be used as names
C# Data Types
A data type specifies the size and type of variable values. It is important to use the correct data
type for the corresponding variable; to avoid errors, to save time and memory, but it will also
make your code more maintainable and readable. The most common data types are:
BY:Moti B:
C# Lab Manual Console
Application
Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are int and long. Which type you should use, depends on the numeric
value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
Valid types are float and double.
C# Type Casting:
Type casting is when you assign a value of one data type to another type.
Implicit Casting: Implicit casting is done automatically when passing a smaller size type to a
larger size type:
Example:
int myInt = 9;
Console.Writeln(myInt); //output ??
Console.Writeln(myDouble); //output ??
Explicit Casting: Explicit casting must be done manually by placing the type in parentheses
in front of the value:
Example:
BY:Moti B:
C# Lab Manual Console
Application
int myInt = (int) myDouble; //manual casting: double to int
Console.Writeln(myDouble); outputs ??
Console.Writeln(myInt); outputs ??
It is also possible to convert data types explicitly by using built-in methods, such
as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long):
using System;
namespace MyApplication{
class Program {
} }}
C# User Input
In the following example, the user can input his or hers username, which is stored in the
variable userName. Then we print the value of userName:
BY:Moti B:
C# Lab Manual Console
Application
Example 1:
Create a string variable and get user input from the keyboard and store it in the variable.
//print the values of variable (username), which will display the input value
Like the error message says, you cannot implicitly convert type 'string' to 'int'
You can convert any type explicitly, by using one of the Convert. To methods:
Example:
using System;
namespace MyApplication{
class Program {
BY:Moti B:
C# Lab Manual Console
Application
static void Main(string[] args)
{
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
}}}
Exercise: Write C# program that can display the result of Arithmetic operator such like the
following output (result) .The numbers are read from the keyboard (enter by user)
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 thee next key pressed by user.This mehod is usually
used to hold the screen until user press a key
C# Operators
Operators are used to perform operations on variables and values.
BY:Moti B:
C# Lab Manual Console
Application
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.
1. Arithmetic Operators
2. Assignment Operators
An assignment operator assigns a value to its left operand based on the value of its right operand.
The simple assignment operator is equal (=), which assigns the value of its right operand to its
left operand. That is, x = y assigns the value of y to x.
BY:Moti B:
C# Lab Manual Console
Application
3. Comparison Operators
Comparison operators are used to compare two values. Operators that compare values
and return true or false.
BY:Moti B:
C# Lab Manual Console
Application
4. Logical Operators
BY:Moti B:
C# Lab Manual Console
Application
5. Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^
are as follows:
Assume if A = 27; and B = 86; then in the binary format they are as follows −
A&&B=?? A^B=???
C# String
In C#, a string is a series of characters that is used to represent text. It can be a character, a
word or a long passage surrounded with the double quotes ("") .C# provides the String data
type to store string literals. A variable of the string type can be declared and assign string
literal, as shown below.
BY:Moti B:
C# Lab Manual Console
Application
Special Characters
A text in the real world can include any character. In C#, because a string is surrounded with
double quotes, it cannot include " in a string. The following will give a compile-time error.
a. String Length:-To get the length of a String, use Length property on string.
BY:Moti B:
C# Lab Manual Console
Application
String.Length returns an integer that represents the number of characters in the string.
b. String Copy:-String Copy method is create a new String object with the same content.
Copy value of the first one to the second and vice versa
Parameters:
Returns:
Exceptions:
BY:Moti B:
C# Lab Manual Console
Application
d. String Concatenation
The + operator can be used between strings to combine them. This is called Concatenation
Console.WriteLine(name);//??
C# Conditional Statement
Conditional statements in C# can be used to take decisions based on certain conditions in your
program. A statement that can be executed based on a condition is known as a “Conditional
Statement”. The statement is often a block of code.
BY:Moti B:
C# Lab Manual Console
Application
1. Conditional Branching
This statement allows you to branch your code depending on whether or not a certain condition
is met. There are different parts of conditional branching.
a. if...Statement: As the name indicates it is quite simple. If a certain condition is satisfied, then
perform some action.
Syntax Example
b. int x =Statement:
if….else 20; An extra
else int bey =added
statement can 18; to an if
condition, toif execute
(x > y)what should
{ if condition is not
happen if the
Console.WriteLine ("x is
satisfied.
greater than y");}
Syntax Example
BY:Moti B:
C# Lab Manual Console
Application
c. if…else if…else statement: If a primary if condition is not satisfied, we can add an Else If
statement in between to check another condition if required.
Syntax:
if (condition1){
else if (condition2){
}else{
Example:
There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands. It can be used to replace multiple lines of code with a single line. It is often used
to replace simple if else statements:
Example:
Console.WriteLine(result);}
BY:Moti B:
C# Lab Manual Console
Application
Note : In the case of the C# Language, using a break after every case block is mandatory, even
for the default.
e. Switch Statement
Syntax:
BY:Moti B:
C# Lab Manual Console
Application
Example:
2. Conditional Looping
What is loops?
A Loop executes the sequence of statements many times until the stated condition becomes
false. A loop consists of two parts, a body of a loop and a control statement. The control
statement is a combination of some conditions that direct the body of the loop to execute until
the specified condition becomes false. The purpose of the loop is to repeat the same code a
number of times.
BY:Moti B:
C# Lab Manual Console
Application
ª Initialization: that sets a starting point of the loop
ª Condition: that sets an ending point of the loop
ª Iteration: that provides each level, either in the forward or backward direction
C# provides 3 loops that allow you to execute a block of code repeatedly until a certain condition
is met; they are:
For Loop
While loop
1. For loop: When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop
Syntax
For(initializar;Conition;iterator)
{
< statement >
Example: How to check whether a given number is EVEN and ODD. The numbers are between
1 and 10 by using for loop
BY:Moti B:
C# Lab Manual Console
Application
2. While loop: The while loop loops through a block of code as long as a specified condition is
true. Do not forget to increase the variable used in the condition, otherwise the loop will never
end!
BY:Moti B:
C# Lab Manual Console
Application
Exercise 1: C# program to find sum of the first five natural Numbers by using while loop
3. Do…While loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax:
Do
{
< statement >
i++;
}
While(Condition)
Example:
using System;
namespace Loop
{
class DoWhileLoop
{
public static void Main(string[] args)
{
int i = 1, n = 5, product;
do
{
product = n * i;
Console.WriteLine("{0} * {1} = {2}", n, i, product);
i++;
}
while (i <= 10);
BY:Moti B:
C# Lab Manual Console
Application
Console.ReadKey();
}}}
C# Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
string[] cars;
To insert values to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:
Console.WriteLine(cars[0]);output?????
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
BY:Moti B:
C# Lab Manual Console
Application
BY:Moti B: