0% found this document useful (0 votes)
12 views17 pages

Introduction To C#: Be Programs

Uploaded by

clashofclane058
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)
12 views17 pages

Introduction To C#: Be Programs

Uploaded by

clashofclane058
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

UNIT-I

Chapter-2

INTRODUCTION TO C#

LIntroduction: C# can be used to develop two categories of programs,


O Executable application programs
D Component libraries

Executable programs are written to carry out certain tasks and require the method Main in one of the classes.

Component libraries do not require a Main declaration because they are not standalone application programs.
They are written for use by other applications.

C# Program

Executable Library

Programs Programs

CLR Application

Output CLR

Output

2, Simple C# Program:

class SampleOne

public static void main0

System.Console, WriteLine("C# is sharper than C+);

Class Declaration :The first line class SampleOne declares a class, which is an object orient construct. Classisa
keyword and declares that a new class definition, that specifies the name of the class to be defined.
The braces: C# is a structured language, meaningcode blocks are always enclosed by braces { and ). Therefore
.everyclass definition in C# begins with an opening brace and ends with a corresponding (
closing braces} that

appears in the line of the program.


last

The main method: the third line


public static void main()

defines a method named Main. Every C# executable program must include the )
Main( method in one of the
classes. This is the staring point for executing the program. A C# applications can have any number of classes but
only one class can have the main method to initialte the execution. This line conaions number of keywords
public,static and void.

public -The keyword public is an access modifier that tels the C# complier that the main method is

accessible by anyone.
Static- the keyword static declares that the Main method is global one and can be called without creating

an instance of the class. The complier stores the address of the method as the entry point and uses this

information to begin execution before objects are created.

Void- The keyword void is a type modifier that states that the Main method does not return any value.
The Output Line: the only executable line in the program is

System.Console, WriteLine("C# is sharper than C++*9;


The method WriteLine is a static method of the Console class, which is located at the namespaceSystem. The
method WriteLine always appends a new line character to the end of the string.
Executingthe Program :After creating the program save it as .cs file extension in a floder. For compiling the
program, go to the folder where you are stored the file and then type the command csc filenamc.cs
The C# compiler(CSC)compile your code and creates an executable file by name filenamc.exc in the same
directory. If there are errors then compiler will produce error messages. Errors shold be corrected and then
compiled again. For rxecuting the program, type in the name of the executable file at the command
prompt.That is filename

3, Namespaces :Namespaces in C# are used to organize too many classes so that it can be casy to handle the

application. In a simple C# program, we use System.Conso le where System is the namespaceand Console is the
class. To access the class of a namespace, we need to use namespacename.classname. We can use using keyword
so that we don't have to use complete name all the time.

using System;

namespace ConsoleApplicationl

class Program

static void Main(string[] args)

Console.WriteLine("Hello !");

4Addin Comments:Comments are used for explaining the code and are used in a similar manner as in Java,
C C+t.Compilers ignore the comment entries and do not exccute them. Generally, programming anguages
or
contain two types ofcomments but in C#, there are 3Types of comments:
1. Single Line Comments :It is used to comment a single line. These comment can be written in a

separate line or along with the codes in the same line. But for better understanding always use the
comment in a separate line.
Syntax :
/Single Line Comments

2. Multiline Comments :It is used to comment more than one line. Generally this is used to comment
out an entire block ofcode statements.

Syntax :
* Multiline

Comment */

5. Main Returning Value: Main( ) can also return a value if it is declared as int instead of void. When the
rturn type is int, we must include a return statement at the end of the method.

using System;

namespace ConsoleApplicationl

class Program

{
static int Main(string] args)

Console. WriteLine("Hello !");


return 0;// return statement

6,Using

can
Aliases

be applied
for

only to
Namesnace
the namespaces
Classes

ad
: System
cannot
is a namespace and Console
be applied to the class. This
is a class,

problem can be avoided


The using directive

by using
aliases for namespaceclasses. The format is

using alias-name = class-name ;


Using A=System.Console;
class SampleFour

public static void Main)


{

A.WriteLine("C# is sharper than C+);

ZPassing String obiects to WriteLine Method: String values can be stored in string objects and usethese
objects as parameters to the WriteLine method. String data type can be used to create a string variable and
assign a string constant.

string S ="SRC»
The content of S may be printed out using the WriteLine method:
System.Console.WrtieLine(S);
8. Comnmand Line Arguments: There may be an occasion when we may like our program to behave in a
particular way depending on the input provided at the time of execution. This can be done using Command line
arguments. Command line arguments are parameter supply to the main method at the time of invoking it for

execution. For example,


static void Main(stringl] args)
You can send arguments to the Main method by defining the method in one of the following ways:
static int Main(string[] args)
static void Main(string] args)
To enable command-line arguments in the Main method in a Windows Forms application, you must manually
modify the signature ofMain in program.cs. The code generated by the Windows Forms designer creates
a Main without an input parameter.
9, Main with a class: In C# programming the Main method is where program starts execution. It is the main
entry point of program that executes all the objects and invokes method to execute. There can be only one Main
method in C#.However, the C# Main method can be void or int return type. It must be inside a class or struct and

must be declared with static modifier. It is the main place where a program starts the execution and end. The Main
method can have a parameter and these parameters are known as zero-indexed command line argument. The
Main method in C# is always declared with static because it can't be called in another method of function. The
Main method instantiates other objects and variables but there is no any method there that can instantiate the main
method in C#. On another hand, the main method doesn't accept parameter from any other function. It only takes
a parameter as an argument via command line argument.

10, Providing interactive Input: Different ways for giving value to the variable are,

1. Using an assignment statement


2. Using command line arguments
3. Using user interactive input

System.Console class provides Read, ReadLine and ReadKey methods to read user inputs.

System.Console.readLine);

11, Using Mathematical Eunctions: The System.Math class in C# provides methods are properties to

mathematical operations, trigonometric, logarithmic calculations, etc. The C# Math class has many
perform
methods that allows you to perform mathematical tasks on numbers.
method can be used to find the highest value ofx and y:
O Math.Max(x,y): The Math. Max(x,y)

Console. WriteLine (Math.Max(5, 10));


method can be used to find the lowest value of of x andy:
O Math.Min(x,v): The Math.Min(x,y)
Console. WriteLine(Math. Min(5, 10);

O Math.Sqrt(r) :The Math.Sqrt(x) method returns the square root ofx:

Console. WriteLine(Math.Sqrt(64);

errors are the errors that occurred when we write the


wrong syntax.
12, ComnileErrors:Compile-time
Time
errors will be
If we write the wrong syntax or semantics ofany programming language, then the compile-time

The will not allow to run the program until all the errors are removed from
thrown by the compiler. compiler
will generate the executable
the program. When all the errors are removed from the program, then the compiler
file.

The compile-time errors can be:


the syntax ofany programming language, then
O ,Syntax errors :When programmer does not follow
the

the compiler will throw the syntax error. For example,

int a, b:

U Semantic errors :The semantic errors exist when the statements are not meaningful to the

compiler.Forexample,
atb=c;
13, Program Structure :An executing C# progr am may contain a nunber coding blocks as shown in
below:

Document Section
Optional

Using Directive Section

Optional
Interfaces Section

Classes Section
Optiona

Main Method Section

Optiona

Essential

0 Documentation section: consists of a set of comments giving the name of the program, the author, ate
and other details, which the programmer may like to use at a later stage.
O Using directive section: will include all those name spaces contain classes required by the application.
This section tells the compiler to look in the namespace specified for these unresolved ciasses.

D Interfaces section :
is similar to a class but contains only abstract members. Interfaces are used when we
want to implement the concept of multiple inheritance in a program.
O Classes section: A C# program may contain multiple class definitions. Classes are the primary and
essential elements of a program. These classes are used to map the objects of real world problems. The
number of classes depends on the complexity ofthe program.
D Main method section :It is the essential part of the program.A program may contain onty this part. The
main method creates objects of various classes and establishes communication between them. On reaching

the end of the main the program terminates and the control passes back to the operating system.

14. Similarities and differences from JAVA:


O Java by relying on what is interpreted bytecode
exists a temporary state that is only resolved by the

JVM this is not compiled on run time execution of the JVM to construct meaningfu!
and relies

assembly code. C# produced assemblies which are compiled code which then run against the CLR this
represents a streamlining of code execution as there is less emphasis on the underlying virtual machine
to produce executable code.

0 Java an open-source based technology


is although it could be moving to a closed source afer the
purchase of Sun by Oracle however this is a contentious/political situation and the fact is Java has its

root firmly in open-source development model, C# is a propriety language namely Microsoft


technology, any licensing is restricted by Microsofi although there are some open source
implementation projects.
O C# underlying infrastructure can be accessed by other languages such as JScript VBScript C++CLI
so a program written in one language can interact with one written in another. Java has nosuch ability.
O Java is also totally platform independent.
LTERALS. VARIABLES AND DATA TYPES

1Literals:A literal is a source code representation of a value.

C# LIterals

Numeric Boolean Character


Literals Literals Literals

Integer Single:
Real' iterals sting Literals
Literals Character
Literals

1. Numeric literals :are divided into Integer literals and real literals.

Integer literals: have two possible forms; decimal and hexadecimal. Decimal integer consists of a
set of digits 0through 9proceeded by an optional minus sign.
123 -321

A sequence of digits proceeded by Ox or 0X is considered as hexadecimal integer. It may include

alphabets A through F or 'a' through 'f


Real literals are used towrite values of types float, double, and decimal.

2. Boolean literals: value are true and false. boolean-literal:true false. The type ofa boolean-literal is bool.

3. Character literais:
A character literal represents a single character, and usually consists of a character in quotes, as
in 'a'.

character-literal:' character

String literals: C# supports two forms of string literals: regular string literals and verbatim string

literals.A regular string literal consists of zero or more characters enclosed in double quotes, as

in "hello", and may include both simple escape sequences (such as\t for the tab character) and

hexadecimal and Unicode escape sequences.

2.Variables; A yariable is a name given to a memory location and all the operations done on the variable
eftects that memory location. In C, all the variables must be declared before they can be used. is the basic

unit of storage in a program. The value stored in a variable can be changed during program execution.

Syntax for variable definition in C# is -


<data type> <variable list>;

Here, datatypemust be a valid C# data type including char, int, float, double, or any user-defined data type, and

variable list may consist ofone or more identifier names separated by commas. For example,
int i, j, k;

char c, ch;

3,DataTypes:
C# Data Types

value Types Reference


Polnters
Types

Predefined User-Defined Predetined User-Defined


Types Types Types Types

Integers Enumerations Objects Classes


Real Numbes Structures Strings Arrays
Booleans
Delegates
Characters Interfaces

Every variable in C# is associated with a data type. Data types specify the size and type of values that can be
stored. C# is language rich in its data types. The variety available allows the programmer to select the type
appropriate to needs of the application. The types in C# are primarily divided into two categories:
Value types
Reference types
Value types and reference types differ in two characteristics:
Where they are stored in memory
How
( they behave in the context of assignment statements

Values types: which are of fixed )


on the stack, and when a value of a variable is assigncd
length are stored to
another variable, the value is actually copied. This means that two identical copies of the value are available in
memory. Value type is further classified as predefined and user defined types.
Predefined types are known as simple types or primitive types,which includes Integer, Real numbers,
Booleans and characters.

User-defined types are known as complex types or primitive types , which includes Enumeration and
Structures

Reference types:( which are variable length) re stored on the heap, and when an assignment between two
reference variables occurs, only the reference is copied; the actual value is remains in the same memory location.

This means that there are two references toa single value. Reference type is furtber classified as predefined and
user defined types.

• Predefined types are known as simple types or primitive types , which includes Objects and

Strings

User-defined types are known as complex types or primitive types , which includes Classes,

Arrays, Delegates and Interfaces

Pointers: The third category of types is called pointers is available for use only in unsafe code. Value types and
reference types are further classified as predefined and user defined types.

Values types (which are of fixed length)are stored on the stack, and when a value of a variable is assigned to
another variable, the value is actually copied. This means that two identical copies of the value are available in

memory. Value type is further classified as predefined and user defined types.
Predefined types are known as simple types or primitive types , which includes Integer, Real numbers,

Booleans and characters.


User-defined types are known as complex types or primitive types , which includes Enumeration and

Structures
Simple Types

Boolean Numeric
Types Character
Types Types

Floating Integrat Decimat


Point Types Types
Types

Signed Unsiged
Types Types

1. Boolean Type: is used when a particular condition is tested, during the execution of the program. There are
only two values that a Boolean type can take: true or false. Both have been declared as a keywords. Boolean
type is denoted by the keyword bool and uses only one bit of storage.
2. Numeric type: is divided into three types :
i.
Floating point type :Floating point numbers represent rcal numbers in computing. Real numbers
measure continuous quantities, like weight, height, or specd. In C# we have threc floating point
types: float, double, and decimal.

Type Size

float
4 bytes

double 8 bytes
ii. Integral type: Integral type can hold whole numbers such as 123,
-96 and 5679. The size of the values that can be stored depends on the Integral data type we choose.
C# supports the concept of unsigned types and therefore it supports eight types of integers.

Signed Integers Unsigned integers

sbyte long byte


ulong

short

ushort uint
int

Signed integers: Signed integer types can hold both positive and negative numbers.
Size Min Value Max value
(Byte)
Sbyte 1 -128 127

Short -32768 32767

Int -2,147,483,648 2,i47,483,647

Long -9,223,372,036,854,775,sos9,223,372,036,854,775,807

b. Unsigned integers: We can increase the size of the positive value stored in an integer type by making
it unsigncd.

byte 255
Ushort 2 65,535
Uint 4 4,294,967,295
Ulong 18,446,744,073,709,551,615
|O.|0
iüü. Decimal Type: is high precision,128 bit data type that is designed for use in financial and monetary
calculations. It can store values in the range I.0 X I10 -28 to 7.9 X I02% with 28 significant digits.

3. Character types: in order to store single character in memory ,C# provides character data type care called

char. The char type assumes a size oftwo bytes but holds a single character.

4. Reference tynes Unlike value types, a reference type doesn't store its value directly. Instead, it stores the
address where the value is being stored. In other words, a reference type contains a pointer to another memory
location that holds the data.

For example, consider the following string variable:


string s = "Hello World!!";

The following image shows how the system allocates the memory for the above string variable.

string s = "Hello World!!";

RAM

Ox600000 Hello Worid!

Actualvalue
Reference type variable
contains address where the

value is stored

Memory Allocation of Reference Type Variable

As you can see in the above image, the system selects a random location in memory (0x803200)for the
variable s. The value ofa variable s is Ox600000,which is the memory address of the actual data value. Thus.
reference type stores the address of the location where the actual value is stored instead of the value itselfThe

followings are reference type data types:

String
Arrays (even if their elements are value types)
Class

Delegate

5. Decalration of variables : A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C# bas a specific type, whichdetermines the size and layout ofthe variable's memory
the range of values that can be stored within that memory and the set of operations that can be applied to the
variable. The general form of declaration of
variable is:
type variable1,variable2, variables,.. .variableN;
variables are separated by commas. A declaration statement ends with semicolon.
Example :int count;
float x,y;

The followings arenaming conventions for declaring variables in C#:


Variable names must be unique.
Variable names can contain letters, digits, and the underscore
only.
Variable names must start with a letter.
Variable names are case-sensitive, num and Num are considered different names.

Variable names cannot contain reserved keywords.

6. Initialization of variables: To create a variable, you must specify the type and assign a value:
=

it
Syntax is datatype variable name value:

The following declares and initializes a variable of an int type.


int num= 100;
Above, int is a data type, num is a variable name (identifier). The = operator is used to assign a value to a

variable. The right side of the operator is a value that will be assigned to left side variable. Above, 100 is
assigned to a variable num.

7.Defanlt values A variable is either explicitly assigned a value or automatically assigned a default value.
The following categories variables are automatically initialized to their default values:
Static variables

Instance variables

Array elements
The default value of a variable depends on the type of the variable.

8. Constant variables: A variable whose value can not be changed during the execution of the program is

called a constant varjable. In C#, a const keyword is used to declare constant fields.and constant' local. The
value of the constant field is the same throughout the program or other
in words, once the constant field is
assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a constant
is a number, string, null reference, boolean values. For example :
const int rows=10:
const int num=30;

9. Scone of Variables: The scope of the variable is the region of code within which the variable can be
accessed. This depends on the type of the variable and place of its declaration. C# defines several categories of
variables. They include:
Static variables

Instance variables

Array elements
Value parameters
Reference parameters

Output parameters
Local variables
Static and instance variables at the class level and are known as fields or field variables. The scope
are declared

of these variables begins at of their declaration and ends when the Main method terminates.
the place
The reference and output parameters do not create new storage locations. Instead they represent the same storage
Jocations as the variables that are passed as arguments. The scope of these variables is always the same as the
underlying variables.
Variables declared inside the methods are called local variables. They are not available for use outside the method
definition. Local variables can also be declared inside program blocks that are defined between an opening braces
{and a closing braces ). The scope of the variables starts immediately after its identifier in the declaration and
extends up to the end of the block contining the declaration. Within the scope of the local variable, it is an error
to declare another local variable with the samne name. For example,
class ABC

static int m;
int n;
void fun( int x, ref int y, out int z, int a)

int j=10;

This code contains the following variables:


m as static variable

n as instance variable

x as value parameter

o y as reference parameter

o zas output parameter

o a[0] as array clenment

o jas local variable

The of Converting a Value Type to a Reference Type is called Boxing.


10. Boxing and Unboxing: operation
assigncd to an objcct without an explicit conversion. When the compiler
Any typc, value or reference can be
box' into which places the value of
type, creates an object

it
needs a reference it
finds a value type where its

the valuc type. For examplc :


int m=100;
object om = m:Il creates a box to hold m
for the object. Note that the boxing operation
when executed this code creates a teporary reference type box

creates a copy of value of the m integer to the object om.


object( reference) Type to a value Type is called Unboxing. We can only unbox
The operation of Converting a

avariable that has previously been boxed.


int m=100;
object om = m; I/ box m
int n=(int) om; /unbox om ack to an int
the value type we request is actually stored in the object under
when performing unboxing, c# checks that

conversion. Only if is , the value is unboxed.


it
we have to ensure that the value type is large enough to hold thc value of the object.
When unboxing a value,
, Introduction:

logical operations.

mathematicaland
An Operator
Operators

logical operations.
are
is

used
OPERATORS AND EXPRESSIONS

a symbol that
in programs
tells the computer to perform certain

to manipulate data and variables. They form


mathematicalor
a part of

2. Arithmetic Onerators: Thefive arithmetic operations supported by the C# languages are:


addition

Subtraction

multiplication
division

% modulo division
:when both the operands in a single arithmetic expression such as a + bare integers,
i.Integer arithmetic
and the operation is called integer arithmetic. For example: at
the expression is called integer expression
b where a=10 b=15
ii. Real arithmetic :when both the operands in a single arithmetic expression such as a +bare real, the

is called real expression and the operation is called real arithmetic. For example :a+ b where
expression
a=10.4 b=15.7
Mixed mode arithmetic: When one the operand is real and the other is integer, the cxpression

is
iii. of

one of the real type, then the other operand


is
called mixed mode arithmetic expression. If either operand

is converted to real and real arithmetic is performed. The result will be real. Thus 15/10.0 produces the
result 1.5 where as 15/10 produces the result 1

3. Relational onerator: In order to evaluate a comparison between two expressions we can use the relationaland

value that can only be true or false,


equality operators. The result of a relational operation is a Boolean

according to its Boolean result. We may want to compare two expressions, for example, to know if they are equal

Here the relational and equality operators that can be used in C#:
or if one is greater than the other is. is a list of

Equal to

Not equal to
Greater than

Less than
Greater than or equal to
Less than or equal to
Y^VT|:
Here there are some examples:
(7=5) I/ evaluates to false

(5 > 4) |l evaluates to true

(3 != 2 ) Il evaluates to true

(6>=6) |l evaluates to true

(5<5) Il evaluates to false

4. Logical onerator: The operator !is the C# operator to perform the Boolean operation NOT it has only one

operand, located at its right, and the only thing that does is to inverse the value of it, producing false if its
it
operand is true and true if its operand is false. Basically, returns the opposite Boolean value of evaluating its
it
operand. For example :
!(5 =5) Il evaluates to false because the expression at its right (5=$ ) is true.

!(6=4) Ilevaluates to true because (6 <= 4) would be false.

!true Il evaluates to false

!false Il evaluates to true


The
The logical operators && and are used when evaluating two expressions to obtain a single' relational result.
||
AND. This two operands
operator && corresponds with Boolean logical operation operation results true if both its

are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a

&&b:
&& operator
a && b

true true true

true false false

false true false


false false false

OR. results true if either one of its


The operator ||
corresponds with the Boolean logical operation This operation

Thus being false only when both operands are false themselves. Here are the possible results
two operands is true.

ofa || b:
I| operator
a a b

||
true true true

true false true

false true true

false false false

S, Assienment Onerator: The assignment operator assigns a value to a variable. a =


5;
value5 to the variable a. The part of the left of the assignment operator(=)Is
This statements assigns integer
as the rvalue (right value). The lvalue has to be variable where
known as the Ivalue (left value) and the right one

as rvalue either a constant, a variable. the


of the operation or any combination of these. The most important
result

always takes place from right to left, and


rule while assigning is the right-to-left rule. The statement operation

never other way :


a=b;
This statement assigns to variable a (the Ivalue) the
value contained in variable b the rvalue). ( The value that was

at all in this operation, and in fact that value is lost.


stored until this moment in a is not considered

(
Increment and decrement operator : Shortening even more some expressions ,the increase operator

or reduce by one the value stored in a variable. They are equivalent


++)and the decrease operator (--) increase

to += lant to -= 1,respectively. Thus


:
c t= 1;

C=c+1;
The three of them increase by one the value ofc.
are all equivalent in its functionality.
probabiy produce different executable code depending
C the three previous expressions
In the early compliers,
on which one was used.
be
be used both as a prefix and as a suffix. That means that
can

it
A characteristic of this operator is that can
it
the variable identifier ( ++a) or after (at+ Although in simple expressions like att or
written either before
).
it
the result of the increase or decrease
+ta both have exactly the same meaning, in other expressions in which
an important difference in thcir meaning.
operation is evaluated as a value in an outer expression they may have

In the case that increase operator is used as a prefix


(++a)
the value is increased before the result of the expression
in the outer expression. In case that it is used as suffix
is evaluated and therefore the increased value is considered
is increased after being evaluated in the outer expression. Notice the difference:
(at+ )the value stored in a
Examplel Example2
B=3; B=3;
A=++B; A=B++;
IlA contains 4, B contains 4 I/ A contains 3.B contains 4

In example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied

to A and then B is increased.

a value thatexpression
7. Conditional onerator: The conditional operator evaluates an expression returning if

is true and a different one if the expression is evaluated as false. Its format is :
Condition ? result1 :result2;
is true the expression will return result 1, if it is not will return result2.
condition
it
If

7=5?4:3: Il returns 3, since 7 is not equal to 5


7=5+ 2 ?4:3; l/ returns 4, since 7 is not equal to 5+2
5>3 ?a:b; IIreturns the value ofa , since 5 is greater than 3
a>b?a:b: l returns whichever is greater a or b
In this example a was 2 and b was 7, so the expression being evaluated (a>b)was not true,thus the first

value specified after the question mark was discarded in favor of the second value ( the one after the colon

)which was b, with a value of 7.

the patterns that represents the values


8. Bitwise operator: Bitwise operator modify variables considering bit

they store.
Operator Equivalent Description
& AND Bitwise AND
OR Bitwise Inclusive OR
XOR Bitwise Exclusive OR
NOT Unary Complement ( bit inversion )
<< SHL Shift Left

SHR Shift Right


Snecial onerator:

Special Operators
Purpose
is
relational operator

as
relational operator

typeof
type operator

sizeof Size operator

new Object creator

.(dot) Member access operator

checked Overflow checking

unchecked Prevention of overflow checking

. Arithmetic ExDressions: An arithmetic expression is a combination of variables , constants and operators

arranged as per the syntax of the language. C#can handle any complex mathematical expressions. Forexample:
res=a*btc;

A= (x+Y)*C;

10. Evaluation of Expressions: Expressions are evaluated using an assignment statement of the form.

variable = expression:

variable is any valid C# variable name. when the statement is encountered, the expression is evaluated first and
the result then replaces the previous value of the variable on the left hand side. All variablesused in the

expressions must be assigned values before evaluation attempted. For example,


X= a*b-c:

11. Precedence of Arithmetic Onerators:_An arithmentic expression without any paraenthisis will be

evaluated from left toright using the rules of the precedence of operators. There are two distinct levels of
arithemetic operators in C#.

High Priority */%


Low Priority +
The basic evalution procedure includes two left-to-right pases through the expressions
the second pass,
.During
,the low
the first

priority
pas ,
the high priority operators are applied as they are encountered. During

operators are applied as they are encountered.

one type of data another type. It is also known as


12. Tvne Conversion:_Type conversion is converting to

Type Casting. In C#, type casting has two forms -


Implicit type conversion -These conversions are performed by C# in a type-safe manner. For example,
from derived classes to base classes.
are conversions from smaller to larger integral types and conversions
type conversion These -
conversions are done explicitly by users using the pre-defined
Explicit

functions. Explicit conversions require a cast operator.

1.Implicit Conversion :We can mix data types in expressions.


For exanmple, m=5 +2.75 ;
statement, Whenever data types are mixed in an expression, C# performs the conversions
is a valid

This process is known as implicit or automatic When the complier encounters


conversion.
automatically.
expressions into sub expressions consisting of one operator and one or two
an expression, divides the
it
operands type differs, the compiler converts one of them to match with
operators. For binary operator, if the
if one of the
rule that the "smaller" type is converted to the wider" type. For example,
the other, using the
for
into float because float is wider than an int.
operand is an int and the other is a float, the int is converted

example,
short b=75;

int a = b; I/ implicit conversion


Explicit conversion :C# permits explicit type conversion of variables or expressions using the type cast operator.

Traditional C casts are augmented in C++ by a function-call notation as a syntactic alternative. The general form is

type_name (expression);

Example: average sum/ float (i);


a function for converting valucs to a designated type.
A type_name behaves as if is

it
ofa given type to another. There are sevcral ways to do
Type casting Operator allows you to convert a data

this in C#:
int i;

float f= 3.14;
I=( int ) f;
Here, the
number 3. 14to an integer value (3), the remainder is lost.
The previous code converts the float
notation:
same thing in C# is using the functional
). Another way to do the
Type casting Operator was ( int betwecn parantheses :
by the type and enclosing the cexpression
the expression to be converted
preceding
i= int(f);
Both ways of type casting are valid in C #.
DECISION MAKING AND BRANCHING

l Introduction

evaluated
: Decision making
or tested by the program, along with
structures requires the programmer to specify one or more conditions tobe
a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

2.the varions forms of if statement:


Simple If Statement: The statement allows conditional execution. syntax

if
Its is:

if(condition)

statement;

Here condition is an integer expression and statement is an executable statement. The statement will be executed
only if the condition has a nonzero value.Whenever an integer expression is being evaluated as a condition, a
nonzero value is understood to mean true" and a zero value to mean "false". Here is a program that will find
the highest value of the three integers.

using System;
void main()
{

int nl,n2,n3;

System.Console. WriteLine("n Enter three integers:");


int max=nl;
ifl(n2>max)
max=n2;
ifl(n3>max)
max=n3;
System.Console. WriteLine ("nThe maximum is:",max);

What actually happens when this program is run, you entered 34,46 and 78. nl=34, n2=46 and n3=78. First
max is assigned 34. Then, since 46 is greater than 34, max is assigned 46. Finally, since 78 is greater than 46,
max is assigned 78,and that value is displayed. The above code makes use oftwo if statements. You can make
use of as many if statements as you need in a program.

The I-Elsestatement:

if(<conditional expression >)

<one or more statements>

else

{
<one or more statements>
}

For example:
if(n-2)
{
System.Console. WriteLine("Even No");

else

System.Console. WriteLine("Odd No");

Nesting of If...Else Statement:


if(<conditional expression >)

if(<conditional expression >)

<one or more statements>

else
<one or more
statements>

else

<one or more statements>

For example:
if(sex is female)

if(balance>5000)

bouns=0.05*balance;

else

bouns=0.02*balance;
}

The Else If ladder:

if(<conditional expression 1>)

<one or more statements>

else if(<conditional expression 2>)

<one or more statements>

else

{
<one or more statements>

For example:
if( avg>70)

grade="distinction":

else if( avg>60)

grade-"First Class";

else

grade=-"Second Class":

If you want to test whether a variable takes one ofa series of values, it's easier to usea
3. Switch Statement:

switch statement than an if statement.

switch(<variable>)

case <value 1>:<one or more statements>


break;
case <value 2>:<one or more statements>
break;
case <value 3>: <one or more statements>
break;
default :<0neor more
statements>
break:

The switch
statement
is found evaluates the value
among the constants
expression and then looks for its vaue among the case constants. If the
default listed. then the
(which is statements in that statement list are executed. Otherwise ifthere is a

optional),
an integer
then thee program breaks to that statement Note that expression must evaluate to
type and that the list.

Example:
constants must be integer
constaits.

switch(monthno)

case 1 :System.Console.WrtiteLine(n
break:
Jamuary ):
case 2: System.Console.
WtüeLine("nFebruary );
break:

case 3 :System Console. WriteL inen March ):


break:
case 4:System.Console.WrtitelLine("n April );
break:
case 5: System Console. WrtitelLine(n May ");
break;

case 6:System.Console.WrineLine("n June ):


break;

case 7:System.Conso le. WrtiteLine"n July );


break:

case &: System.Console. WrtiteLine("n August ");


break;

case 9:System.Console. WriteLine(nSeptember "):


break;

case 10: System.Console. WrtieLine("n October );


case 11 : break:

System Consoje. WrtteLine(n November


break;
);
case 12: System.Console. WrtiteLine("n December );

;
break;

default :cout<<"n Invalid Month Number


break;

4. 4alltthrough in switch statement :In the absence of break statement in a case block, if the control moves
to the next case block without any problem, is known as "falthrough". C# does not permit automatic
it
Fallthrough, if the case block contains executable code. It is allowed if the case block is empty. In such cases goto
statement is used. The goto mechanism enables to jump backward and forward between cases and therefore
arrange labels arbitrarily. For example:
Switch(m)

defaut:xy-m;
break;

case 2:x=ytm;
goto default:
case 1:x=Y;
goto case 2:

5,
ternary
The 2: Onerator
operator. It
: C#inchudes
is the short form
a decision-making operator
of the if else conditions.
?: which is called the conditional operatoror

Syntax :condition ? statement 1 :statement 2

If this condition evaluates to true then will execute


The ternary operator with a boolean condition.
it
starts

the first statement after ?. otherwise the second statement after :will be executed.

Page 17

You might also like