You are on page 1of 28

C# Lab Manual Console

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:

Mobile applications Web sites

Desktop applications Games

Web applications VR

Web services Database applications

Why Use C#?

 It is one of the most popular programming language in the world


 It is easy to learn and simple to use
 It has a huge community support
 C# is an object oriented language which gives a clear structure to programs and allows code
to be reused, lowering development costs.
 As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice
versa

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 1: using System means that we can use classes from the System namespace.

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

If you omit the using System line, you would have to write System.Console.WriteLine () to


print/output text.

Note: Every C# statement ends with a semicolon ;.

Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.

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

Console. WriteLine ("Hello World!");

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

Console. WriteLine ("Hello World!");

C# Variables

Variables are containers for storing data values.

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

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax: type variableName = value;

Where type is a C# type (such as int or string), and variableName is the name of the variable


(such as x or name). The equal sign is used to assign values to the variable.

BY:Moti B:
C# Lab Manual Console
Application
Example: Create a variable called name of type string and assign it the value "Besufikad":

String name = “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:

Change the value of myNum = 50

int myNum = 25;

myNum = 50;//myNum now is 50

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:

Const int myNum = 25;

MyNum = 50; //Error

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.

Display Variables: The WriteLine() method is often used to display variable values to the


console window. To combine both text and a variable, use the + character:

Example: string name = “Habtamu”;

Console.Writeln (“Hello” + name);

You can also use the + character to add a variable to another variable: see the following example:

String fristname = “Tesfaye”;

String lastname = “Abush”;

String fullname = fristname + lastname;

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

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

Example: //Good

int minutesPerHour = 60;

// ok ,but not so easy to understand what m actually is

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:

Numbers: Number types are divided into two groups:

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.

In C#, there are two types of casting:

 Implicit Casting (automatically) - converting a smaller type to a larger type size


char -> int -> long -> float -> double

 Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char

Implicit Casting: Implicit casting is done automatically when passing a smaller size type to a
larger size type:

Example:

int myInt = 9;

double myDouble = myInt; //Automatic casting : int to double

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:

Double myDouble = 9.15;

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

Type Conversion Methods

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 {

static void Main(string[] args) {

int myInt = 10;

double myDouble = 5.25;

bool myBool = true;


Output/Result
Console.WriteLine(Convert.ToString(myInt)); // Convert int to string
???
Console.WriteLine(Convert.ToDouble(myInt)); // Convert int to double

Console.WriteLine(Convert.ToInt32(myDouble)); // Convert double to int

Console.WriteLine(Convert.ToString(myBool)); // Convert bool to string

} }}

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:

//Type your username and press enter

Console.Writeln(“Enter your username:”);

Create a string variable and get user input from the keyboard and store it in the variable.

String userName = console.Readline();

//print the values of variable (username), which will display the input value

Console.Writeln(“Username is:”+ userName);

User Input and Numbers

The Console.ReadLine() method returns a string. Therefore, you cannot get information from


another data type, such as int. The following program will cause an error:

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)

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

There are different types of operators. Those are:

1. Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations:

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.

Assignment operators are used to assign values to variables.

A list of all assignment operators:

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

 Logical operators are used to determine the logic between variables or


values

 operators that combine multiple Boolean expressions or values and provide a


single Boolean output

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 = 0011 1100 B = 0000 1101

A&&B=?? A^B=???

A||B =?? ~A==??

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.

Example: String type variables


string ch = "S";
string word = "String";
string text = "This is a string.";

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.

Example invalid string: String text = “This is a “string” in C#.”;

C# includes escaping character \ (backslash) before these special characters to include in a


string. Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc.
to include it in a string. Example escape char \

string text = "This is a \"string\" in C#.";


string str = "xyzdef\\rabc";
string path = "\\\\mypc\\ shared\\project";

There are different types of strings. Those are:

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

String = string. Copy (string str)

Parameters:

String str : The argument String for Copy method

Returns:

 String : Returns a new String as the same content of argument String

Exceptions:

 System.ArgumentNullException: If the argument is null.

Example of String copy


string str1 = null;
string str2 = null;
str1 = "CSharp Copy() test";
str2 = string.Copy(str1); Console.WriteLine(str2);
C. String Compare
C# String.Compare method compares two strings in C#. You can also use C# String. Equals
method and String Comparer class and its method. Example:

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

You can also use the string.concat() method to concatenate to strings

string firstName = “Teklu";

string lastName = “Daniel";

string name = string.Concat(firstName, lastName);

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.

The following are the 2 types:

1. Conditional Branching 2. Conditional Looping

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

int time = 20;


if (time < 18) {
Console.WriteLine("Good
day.");
}
else
{ Console.WriteLine("G
ood evening.");
}
// Outputs "Good evening."

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

// block of code to be executed if condition1 is True

else if (condition2){

// block of code to be executed if the condition1 is false and condition2 is True

}else{

// block of code to be executed if the condition1 is false and condition2 is False }

Example:

int time = 22;


BY:Moti B:
if (time < 10)
{
C# Lab Manual Console
Application

d. Short hand if…else (Ternary operator)

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:

Syntax: variable = (condition) ? expression True : expression False;

Example:

{ int time = 20;

string result = (time < 18) ? "Good day." : "Good evening.";

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

A switch statement takes an expression and evaluates it.


fo r each result of the evaluation, it executes statements. This is known as a case statement.
break statement must be present at the end of each case.
default case is executed if any of the case is not satisfied.

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.

Each and every loop requires the following 3 things in common.

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

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

 To declare an array, define the variable type with square brackets:

string[] cars;

To insert values to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:

string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };

To create an array of integers, you could write:

int[] myNum = { 10, 20, 30, 40 };

Access the Elements of an Array

• You access an array element by referring to the index number.

• This statement accesses the value of the first element in cars:

string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };

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:

You might also like