Skip to main content
PROGRAMMING IN C#
Chapter : 1
Introducing C#
What is C#?
 Is a compute-programming language developed by
Microsoft Corporation, USA.
 Is fully object-oriented language.
 Is first Component-oriented language.
 Suitable for developing Web-based applications
 Designed for developing robust, reliable & durable
components to handle real-world applications.
Highlights of C#
 Derived from C/C++ family.
 It simplifies & modernizes C++.
 It is only component oriented language available today.
 It is a language designed for the .NET Framework.
 It is a concise, lean & modern language.
 It combines the best features of many commonly used
languages: the productivity of VB, the power of C++, & the
elegance of Java.
 It is intrinsically object-oriented & web-enabled.
 It has a lean & consistent syntax.
 Is simple, robust & productive.
 Major parts of .NET Framework are actually coded in C#.
Why C# ?????
 The primary motivation while developing any language is the concern that it able to
handle the increasing complexity of programs that are robust, durable &
maintainable.
 The history of major languages developed is as follows:
BPCL B
C
C++
ANSI C
Oak
Java
ANSI C++
C#
1967 1970
1972
1983
1987
1991
1995
1996
2000
Dennis Ritchie
Bjarne Stroustrup
ANSI Committee
James Gostling
Sun MicroSystems
ANSI Committe
Microsoft
Martin Richards Ken Thompson
Cont….
 C & C++ languages suffer from a
number of shortcomings in
meeting World Wide Web
requirements & standards.
 Some are as follows:
1. The high complexity of language
2. They are not truly object
oriented
3. They have poor type safety
4. They are not suitable for
working with new web
technologies.
5. They do not support versioning
6. Their low productivity
7. They are weak in consistency
8. Their poor compatibility with
the existing systems
 VB, a language promoted by
Microsoft for overcoming these
problems, is not truly object-
oriented and becomes
increasingly difficult to use when
systems become large.
 Java which is truly object-
oriented has not retained some
powerful C++ features such as
operator overloading.
 Java also lacks inter-operability
with code developed in other
languages.
 Microsoft therefore decided to
design a new language.
 The result is C#, a simple &
modern language that directly
addresses the needs of
component-based software
development.
Evolution of C#
 The Internet is the mainstream
for many business organization
today.
 There were a number of
limitations in using the WWW
over the Internet:
1. We could see only one site at a
time
2. The site had to be authored to our
hardware environment
3. The information was basically
read-only.
4. We could not dynamically
compare similar information
stored on different sites.
5. The internet is a collection of
many information islands that do
not co-operate with each other.
 Microsoft wanted to develop a
software platform which will
overcome these limitations &
make the Web both
programmable and intelligent.
 The outcome is a new generation
platform called .NET.
 Microsoft introduced C# as a de
facto language of the .NET
platform.
 C# has been particularly designed
to build software components
for .NET and it supports key
features of .NET natively.
 C# compiler is embedded into
.NET as shown below:
.NET Framework
.NET Platform
C#
Cont…
 C# is a descendant of C++ which in turn is a
descendant of C as illustrated below:
C
C++
Java C# VB
Concept
ProductivityElegance
Concept
Component
Orientation
Object
Orentation
Power
Characteristics of C# (5 marks)
 Simple
 C# simplifies C++ by eliminating irksome operators such as ->, ::, and pointers.
 C# treats integers & Boolean data types as entirely different types.
 Consistent
 C# supports an unified type system which eliminates the problem of varying ranges of
integer types.
 All types are treated as objects.
 Modern
 C# is called modern language bcoz it supports:
 Automatic garbage collection
 Rich intrinsic model for error handling
 Decimal data types for financial applications
 Modern approach to debugging
 Robust security model
 Object-Oriented
 C# is truly object-oriented. It supports:
 Encapsulation
 Inheritance
 Polymorphism
Cont….
 Type-Safe
 Type safety promotes robust programs.
 C# incorporates number of type-safe measures:
 All dynamically allocated objects & arrays are initialized to zero
 Use of any uninitialized variables produces an error message by the compiler
 Access to arrays are range-checked
 C# does not support unsafe casts
 C# supports automatic garbage collection
 Versionable
 Making new versions of software modules work with the existing applications is
known as versioning
 C# provides support for versioning with the help of new & override keywords.
 Compatible
 C# enforces the .NET common language specifications & therefore allows inter-
operation with other .NET languages
 Interoperable
 C# provides support for using COM objects, no matter what language was used to
author them.
 Fexible
 We may declare certain classes & methods as ‘unsafe’ and then use pointers to
manipulate them.
Applications of C#
 C# is a new language developed exclusively to
suit the features of .NET platform.
 It can be used for a variety of applications that
are supported by the .NET platform
 Console applications
 Windows applications
 Developing Windows Controls
 Developing ASP .NET Projects
 Creating Web Controls
 Providing Web Services
 Developing .NET component library
How Does C# differs from C++ ?
 Changes Introduced
1. C# compiles straight from source code to executable
code, with no object files
2. In C#, class definition does not use a semicolon at
end
3. The first character of Main() function is capitalized
4. C# does not support #include statement
5. C# does not support multiple code inheritance
6. Casting in C# is much more safer then C++
7. C# does not support default arguments
8. C# permits declaration of variables between goto &
label
How Does C# differs from C++ ?
 C++ Features Dropped
1. Macros
2. Multiple Inheritance
3. Templates
4. Pointers
5. Global Variables
6. Typedef statement
7. Default Arguments
8. Forward Declaration of Classes
 Enhancements to C++
1. Automatic Garbage Collection
2. Versioning Support
3. Strict Type-Safety
4. Properties to access data members
5. Delegates & Events
6. Boxing & Unboxing
7. Web Services
How Does C# differs from Java ?
1. C# has more primitive data types
2. Arrays are declared differently in C#
3. C# supports struct type & Java does not
4. Java does not provide for operator overloading
5. C# provides for better versioning support than Java
6. C# provides static constructors for initialization
7. Java does not directly support enumerations
8. C# uses is operator instead of instanceof operator in
Java
9. C# checks overflows uses checked statements
10. There is no labeled break statement in C#. The goto
statement is used to achieve this.
11. In Java, the switch statement can have only integer
expression, while C# supports either an integer or string
expressions
Chapter : 2
Understanding .NET: The C# Environment
The .NET STRATEGY
 .NET is a software framework that includes
everything required for developing software for
web services.
 It integrates presentation technologies,
component technologies & data technologies on a
single platform so as to enable users to develop
Internet applications.
The Origins of .NET Technology
 The current technology of .NET has gone through three different phases of development:
 OLE technology
 COM technology
 .NET technology
 OLE (Object Linking & Embedding) technology
 Developed by Microsoft to enable easy inter-process communications.
 OLE provides support to achieve following:
 To embed documents from one application into another application
 To enable one application to manipulate objects located in another application
 COM Technology:
 Overcomes the problems of maintaining and testing of software.
 A program can be divided into number of independent components where each one offers a
particular service.
 Each component can be developed & tested independently and then integrated into the main
system.
 This technology is known as Component Object Model (COM) and the software built using COM is
referred to as componentware.
 Benefits:
 Reduces Complexity
 Enhances software maintainability
 Enables distributed development acrossmultiple organizations
The Origins of .NET Technology (cont…)
 .NET Technology
 Is third generation component model
 Provides a new level of inter-operability compared to COM technology
 Inter-module communication is achieved using Microsoft Intermedia
Language (MSIL) or simply IL
 IL allows for true cross language integration
 IL also provides metadata : describes characteristic of data including
datatypes & locations.
 .NET also includes host of other languages & tools that enable us to
develop & implement Web-based applications easily.
Fig : Three generations of component model
OLE Technology
COM Technology
.NET Technology
Interprocess Communication
Intermodule Communication
Intersite Communication
Phase I – Early 1990s
Phase II – 1995
Phase III – Late 1990s
The .NET Framework
.NET Framework
.NET Building .NET Device
Block Services Software
.NET Platform
.NET User
Experience
.NET Infrastructure
& Tools
Visual Studio .NET Experience
.NET Services
.NET Infrastructure & Tools
Windows .NET .NET Framework
The .NET Framework (cont…)
 The .NET framework is one of the tools provided by the .NET
infrastructure & tools component of the .NET platform.
 The .NET framework provides an environment for building, deploying &
running web services & other applications.
 It consists of three distinct technologies:
 Common Language Runtime
 Framework Base Classes
 User & program interfaces(ASP .NET)
Framework Base Classes
.NET Framework
ASP .NET
(Web Services)
Windows Forms
(User Interface)
Common Language Runtime
The Common Language Runtime (CLR)
 Is heat & soul of the .NET framework
 Is responsible for loading & running C#
programs.
 Supports cross-language interoperability.
 Services provided:
 Loading & execution of programs
 Verification of type-safety
 Providing metadata
 Memory management
 Enforcement of security
 Interoperability with other systems
 Managing exceptions & errors
 Debugging
Components of CLR (cont…)
Intermedia Language (IL)
Common Type System
Common Language Runtime
Execution Support Functions
Security
Garbage Collection
Class Loader
Memory Layout
Framework Base Classes
 Allows to implement applications quickly
 The functionality of the base framework classes resides in
the namespace called System
 Provides:
 Input/Output operations
 String handling
 Managing arrays, lists,maps,etc
 Accessing files & file systems
 Accessing the registry
 Security
 Windowing
 Database management
 Drawing
 Managing errors & exceptions
 Connecting to Internet
User & Program Interfaces
 The .NET framework provides the following tools
for managing user & application interfaces:
 Windows forms
 Web forms
 Console applications
 Web Services
 These tools enables users to develop user-friendly
desktop-based as well as web-based applications.
Benefits of the .NET Approach
 The .NET technology provides a number of benefits to
developers & users.
 Some of them are:
 Simpler & faster systems development
 Enhanced built-in functionality
 Many different ways to communicate with the outside
world
 Integration of different languages into one platform
 Easy execution
 Wide range of scalability
 Interoperability with existing applications
 Fewer bugs
 Potentially better performance
Chapter : 3
Overview of C#
Introduction
 C# can be used to develop two categories of
programs:
 Executable application programs &
 Component libraries
 Executable programs are written to carryout
certain tasks & require Main method in one of
the classes.
 Component libraries do not require Main
declaration because they are not standalone
application programs.
 They are written for use by other applications.
A Simple C# Program
class SampleOne
{
public static void Main()
{
System.Console.WriteLine(“C# is sharper than C++”);
}
}
 Executing the program
 Save the above file with SampleOne.cs name
 Compile as : csc SampleOne.cs
 C# compiler compiles your code and create an executable
file by name
 SampleOne.exe
 For executing the program, simply type in the name of the
executable file at the command prompt.
NAMESPACES
System.Console.WriteLine();
 Here System is a namespace in which the Console class is
located.
 This class can be accessed using the dot operator.
 C# supports using directive that can be used to import the
namespace System into the program.
using System;
class SampleTwo
{
public static void Main()
{
Console.WriteLine(“Hello World!!!”);
}
}
Adding Comments
 Enhances readability & understanding of the
code.
 Programs should have information such as
implementation details, change history and tasks
performed.
 Types of comments:
 Single-line comments (//)
 Multiline comments (/* ….. ….. */)
Main Returning a Value
 Main() can also return a value if it is declared as int instead of
void.
 When the return type is int, we must include a return statement
at the end of the method.
using System;
class SampleThree
{
public static int Main()
{
Console.WriteLine(“Hello World!!!”);
return 0;
}
}
 The value returned serves as the program’s termination status
code.
 It allows communication of success or failure to the execution
environment.
Using Aliases for NAMESPACE Classes
using A=System.Console;
class SampleFour
{
public static void Main()
{
A.WriteLine(“Hello World!!!”);
}
}
Passing String Objects to WriteLine Method
using System;
class SampleFive
{
public static void Main()
{
string name=“PentaSoft Technologies”;
Console.WriteLine(name);
}
}
Command Line Arguments
 Can be used to take an input from a user.
 Command line arguments are parameters supplied to the
Main method at the time of invoking it for execution
using System;
class SampleSix
{
public static void Main(string[] args)
{
string name=“Welcome to”;
Console.Write(name);
Console.Write(“ ”+args[0]);
Console.WriteLine(“ ”+args[1]);
}
}
MAIN with a Class
class Demo //class definition
{
public void display()
{
System.Console.WriteLine(“In Demo Class”);
}
}
class SampleSeven
{
public static void Main(string[] args)
{
Demo d=new Demo(); //creating d object
d.display(); //callinf display() function
}
}
Providing Interactive Input
using System;
class SampleEight
{
public static void Main(string[] args)
{
Console.Write(“Enter Your Name”);
string name=Console.ReadLine();
Console.WriteLine(“Hello ”+name);
}
}
Using Mathematical Functions
using System;
class SampleNine
{
public static void Main(string[] args)
{
double x=5.0;
double y;
y=Math.Sqrt(x);
Console.WriteLine(“y = ”+y);
}
}
Multiple Main Methods
 In C# it is possible to have Main
method in different classes.
 In such situations there would be
multiple entry points in the
program.
 There should be only one.
 This problem can be resolved by
specifying which Main is to be
used to the compiler at the time
of compilation:
 csc filename.cs/main:classname
 Example :
 multimain.cs/main:Class
OR
 multimain.cs/main:Class B
//multimain.cs
using System;
class A
{
public static void Main()
{
Console.Write(“Class A”);
}
}
class B
{
public static void Main()
{
Console.Write(“Class B”);
}
}
Compile Time Errors
 A program is never totally error-free
 Types of errors:
 Syntax Errors
 Logic Errors
 Syntax errors will be caught by the
compiler
 Logical errors should be eliminated by
testing the program logic carefully.
 When the compiler cannot interpret
what we are attempting to convey
through our code the result is syntax
error.
 Example:
using Systom;
class SampleTen
{
public static void main()
{
Console.Write(“Hello”);
}
}
 Errors.cs(2.7): error cs0234: The type
or namespace name ‘Systom’ does not
exists in the class or namespace
 The error message contains:
1. Name of the file being
compiled(Errors.cs)
2. Line number & column position of the
error(2.7)
3. Error code as defined by the compiler
(cs0234)
4. Short description of error
Program Structure
 The documentation section
consists of a set of comments
giving the name of the
program, the author, date &
other details.
 The using directive section
includes all those namespaces
that contain classes required
by the application
 A interface is similar to a
class but contains only
abstract classes.Used in
multiple inheritance
 A C# program may contain
multiple class definitions.
 Every C# program requires a
Main method as its starting
point, the class containing the
Main is the essential part of
program.
Documentation Section
Using Directive Section
Interfaces Section
Classes Section
Main Method Section
Optional
Optional
Optional
Optional
Essential
Chapter : 4
Literals, Variables & Data Types
Literals
 Literals are the value constants assigned to
variables in a program.
 C# supports seven types of literals.
 Integral Literals : Decimal & Hexadecimal Integers
 Real Literals
 Boolean Literals :True / False
 Single Character Literals
 String Literals
 Backslash Character Literals : a, b, n, t, , ”
Variables
 Is an identifier that denotes a storage location used to store
data value.
 May take different values at different times during
program execution.
 Name should be meaningful.
 May consist of alphabets, digits & the underscore.
 Conditions:
 Not begin with a digit
 Uppercase & lowercase are distinct
 It should not be a keyword
 White space is not allowed
 Name can be of any length
Data Types
 Every variable in c# is associated with a data type
 Specifies the size and type of values that can be stored
 Types in C#
 Value types
 Reference types
 Pointers
 Values types are stored on stack
 When a value of a variable is assigned to another variable,
the value is actually typed.
 Reference types are stored on heap
 When a value of a variable is assigned to another reference
variable, only the reference is copied.
Taxonomy C# data types
C# Data Types
Value Types Pointers Reference Types
Predefined
Types
User-defined
Types
Predefined
Types
User-defined
Types
•Integers
•Real Numbers
•Booleans
•Characters
•Classes
•Arrays
•Delegates
•Interfaces
•Objects
•Strings
•Enumerations
•Structures
Declarations of Variables
 Variables are names of storage locations.
 Declaration does three things
1. Tells the compiler what the variable name is.
2. Specifies what type of data the variable will hold.
3. The place of declaration decides the scopeof variable.
 Syntax:
 type variable1, variable2,……. variableN
Default Values
 A variable is either explicitly assigned a value or automatically
assigned a default value.
 Following categories of variables are automatically initialized to
their default values.
 Static variables
 Instance variables
 Array elements
Type Default Value
All integer types 0
char type ‘x000’
float type 0.0f
double type 0.0d
decimal type 0.0m
bool type false
enum type 0
All reference type null
Constant Variables
 Variables whose values do not change during the
program execution are known as constants.
 Eg.
 const int Rows=10
 const int Cols=10
 Advantages
 Programs are easier to read & understand
 Programs are easier to modify
 Accidental errors are minimized
Scope of Variables
 It is region of code within which the variable can be accessed.
 Depends on type of the variable and its place of declaration.
 Consider following Eg…
class ABC
{
static int m;
int n;
void fun(int x, ref int y, out int z, int[] a)
{
int j=10;
……..
……..
}
}
 Static variables
 Declared at the class level
 Known as fields or field variables.
 The scope of these variables begins at the place of their declaration & ends when the
Main method terminates.
 The value parameter ‘x’ will exists till the end of fun() method
 The reference & output parameters (y & z) do not create a new storage locations.
 Their scope is same as the underlying variables that are passed as arguments.
 Array element a[0] come into existence when an array instance is created, & cease
to exist when there are no references to that array instance.
 Variables declared inside a method are called local variables.
 Their scope is until the end of block inside which they are declared.
Boxing & Unboxing
 In OOP, methods are invoked with the help of objects.
 Value types such as int & long are not objects, we cannot
use them to call methods.
 C# achieve this through a technique called as boxing.
 Boxing means the conversion of a value type on the stack to
a object type on the heap.
 The conversion from an object type back to a value type is
known as unboxing.
Boxing
 Any type, value or reference can be assigned to an object without an explicit
conversion.
 When a compiler finds a value type where it needs a reference type, it creates an
object ‘box’ into which it places the value of the value type.
 Example:
int m=100;
object om=m; //creates a box to hold m
 This code creates a temporary reference type ‘box’ for the object on heap.
 This can also be done with:
int m=100;
object om=(object)m; //C-style casting
 Here the variable m & om exist but the value of om resides on the heap. The values
are independent of each other.
int m=100;
object om=m;
m=20;
Console.WriteLine(m); //m=20
Console.WriteLine(om); //om=10
Unboxing
 It is the process of converting the object type back to the
value type.
 We can only unbox a variable that has previously been
boxed.
 Unboxing is an explicit operation using C-style casting.
int m=100;
object om=m; //box m
int n=(int)om; //unbox om back to an int
 When unboxing a value, we have to ensure that the value
type is large enough to hold the value of the object.
Chapter : 5
Operators & Expressions
Type of Operators
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment & decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators
Operator Symbol Action Example
Addition + Adds two
operands
x + y
Subtraction - Subtracts the 2nd
operand with 1st
operand
x – y
Multiplication * Multiplies two
operands
x * y
Division / Divides two
operand
x / y
Modulus % Gives the
remainder when
the operands are
divided.
x % y
Exercise
 Write a program to demonstrate use of all
Arithmetic operators.
Relational Operators.
 Relational operators are used to compare
expressions.
 An expression containing a relational operator
evaluate to either true(1) or false (0).
Relational Operators.
Syntax: (ae-1 relational operator ae-2)
Operator Symbol
Equal ==
Greater than >
Less Than <
Greater than or equal to >=
Less than or equal to <=
Not Equal to !=
Exercise
 Write a program to demonstrate use of relational
operators.
Logical operators
 Logical operators helps a user to combine two or more relational
expressions into a single expression.
Operator Symbol
AND &&
OR ||
NOT !
Bitwise logical AND &
Bitwise logical Or |
Bitwise logical exclusive Or ^
The Assignment Operator:-
 Used to assign the value of an expression to a variable.
 The assignment operator is the equal sign (=).
Syntax : variable = expression;
For e.g. a=b;
 C# also has a set of short assignment operator.
 Syntax: v op=exp
 Here ‘v’ is a variable, ‘exp’ is an expression & ‘op’ is an C# binary operator.
 The operator op= is known as shorthand assignment operator.
 Example:
 x+ = y+1; is same as x=x+(y+1);
 Advantages of shorthand assignment operators:
 Easier to read.
 The statement is more concise
 Results in more efficient code
C# Unary mathematical operators:-
Operator Symbol Action Examples
Increment ++ Increments the
operand by one
++x, x++
Decrement -- Decrements the
operand by one
--x, x--
Prefix and Postfix modes
 When used in prefix mode, the increment and
decrement operators modify their operand before
it’s used.
 When used in postfix mode, the increment and
decrement operators modify their operand after
it’s used.
Exercise:-
 Write a program to demonstrate prefix and
postfix modes.
Conditional Operator
 Is C#’s only ternary operator.
 Takes three operators.
 Syntax : exp1 ? exp2 :exp3;
Here if exp1 evaluates to true, then value of exp2
is assigned else of exp3.
 Eg.
a=10;
b=15;
x = (a > b) ? a :b;
Operator Precedence and Parentheses
 Some rules are needed about the order in which operations are
performed.
 This order, called operator precedence, is strictly spelled out in
‘C# ‘
Operators Relative Precedence
* / % 1
+ - 2
Type Conversion
 Used to convert data of one type to another type.
 Example:
byte b1=10;
byte b2=20;
byte b3=b1+b2;
 Results in an error message because, when we add two
byte values, the compiler automatically converts them into
int types and the result is an integer.
 Hence code should be:
int b3=b1+b2; //no error
 Ways of Type Conversion
 Implicit Conversions
 Explicit Conversions
Type Conversions
Implicit
Conversions
Explicit
Conversions
Arithmetic
Operations
Casting
Operations
Mathematical Functions
 Present in Math class of System Namespace.
 Static Members: E and PI
 Mathematical Methods in Math class:
Method Description
Sin() Sine of an angle in
radians
Cos() Cosine of an angle in
radians
Tan() Tanget of an angle in
radians
Asin() Inverse of Sine
Acos() Inverse of Cosine
Atan() Inverse of Tangent
Sinh() Hyperbolic sine
Cosh() Hyperbolic cosine
Tanh() Hyperbolic tangent
Sqrt() Square Root
Pow() Number raised to a
given power
Exp() Exponential
Log() Natural logarithm
Abs() Absolute value
Min() Lower of two numbers
Max() Higher of two numbers
Exercise:-
 Write a program to find square root of number 25
 Write a program to find minimum between two
numbers 25 & 35 using Math class.
Chapter : 6
Decision Making & Branching
The if Statement
 Is a powerful decision making statement
 Used to control the flow of execution of
statements
 General form:
if (boolean-expression)
{
statement-block;
}
statement-x;
Flowchart of simple if control
boolean
expression
?
Statement
block
Statement-X
Next statement
False
True
Entry
Jumping
Exercise
 Write a program that stores weight & height of
10 person in array & count number of person
with height greater than 170 & weight more than
55.
The IF….. ELSE Statement
 Is an extension of if statement.
 General form:
if (boolean-expression)
{
true-block statement (s);
}
else
{
false-block statement (s);
}
statement-x;
Flowchart of if…else control
boolean
expression
?
True-Block
Statement
Statement-X
Next statement
FalseTrue
Entry
False-Block
Statement
Exercise
 Write a program that counts total of even & odd
numbers stored in an array ‘number’.
Nesting of If….Else Statements
 Used when a series of decisions are involved.
 General form:
if (test condition1)
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
Flowchart of nested if….else statements
Test
condition1
?
Statement-3
Statement-X
Next statement
True
False
Entry
Statement-1
Test
condition2
?
Statement-2
TrueFalse
Exercise
 Write a program that finds largest among 3
numbers using nested if..else statement.
The Else If Ladder
 Used when multipath decisions are involved.
 It is an chain of ifs in which the statement associated with each else is an
if.
 General form:
if (condition 1)
statement-1;
else if (condition 2)
statement-2;
else if (condition 3)
statement-3;
else if (condition n)
statement-n;
else
default-statement;
statement-x;
Exercise
 Write a program that finds the grade of a student
using else if ladder.
The Switch Statement
 If statements increases complexity of a
program dramatically as the
alternatives increases.
 The program becomes difficult to read
& follow.
 C# offers an alternative with the help of
switch statement
 General Form:
switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
--------------------
--------------------
--------------------
default:
default-block
break;
}
statement-x;
 Here, the expression must be an integer
type or char or string type
 Value-1, value-2 … are constants or
constant expressions & are known as
case labels.
 Block-1, block-2…… are statement lists
and may be zero or more statements.
Example
using System;
class CityGuide
{
public static void main()
{
Console.WriteLine(“Select your choice”);
Console.WriteLine(“London”);
Console.WriteLine(“Bombay”);
Console.WriteLine(“Paris”);
Console.WriteLine(“Type your choice”);
String name = Console.ReadLine ( );
switch (name)
{
case “Bombay”:
Console.WriteLine(“Bombay : Guide 5”) ;
beak;
case “London”:
Console.WriteLine(“london : Guide 10”) ;
beak;
case “Paris”:
Console.WriteLine(“Paris : Guide 15”) ;
beak;
default:
Console.WriteLine(“Invalid choise”) ;
break;
}
}
}
Fallthrough in Switch Statement
 In the absence of the break
statement in a case block, if the
control moves to the next block
without any problem, it is known
as ‘fallthrough’.
 Fallthrough is permitted in C, C+
+ & Java.
 C# does not permit automatic
fallthrough, if the case block
contains some code.
 However, it is allowed if the case
block is empty.
 If we want two consecutive case
blocks to be executed
continuously, we have to force the
process using the goto statement.
 Example
switch(m)
{
case 1:
x=y;
goto case2;
case 2:
x=y+m;
goto default;
default:
x=y-m;
break;
}
Chapter : 7
Decision Making & Looping
The While Statement
 The process of repeatedly
executing a block of statements is
known as looping.
 Is an entry-controlled loop
statement.
 The test condition is evaluated
and if the condition is true, then
the body of the loop is executed.
 Syntax:
initialization;
while(test condition)
{
Body of the Loop…
}
 Entry based loop
Body of the
loop
Test
cond
True
False
Example
class DowhileTest
{
public static void Main ( )
{
int two,count,y;
two = 2;
count=1;
System.Console.WriteLine("Multiplication Table n");
while(count<=10)
{
y = two * count ;
System.Console.WriteLine("2 * " + count + " = " + y) ;
count = count + 1;
}
}
}
The Do Statement
 On some occasions it might be
necessary to execute the body of
the loop before test is performed
 This can be handled using do
statement.
 Is an exit-controlled loop
statement.
 The body of the loop is executed
at least once.
 Syntax:
initialization;
do
{
Body of the Loop…
}while(test condition);
Body of the
loop
Test
cond
• Exit based loop
False
True
Example
class DowhileTest
{
public static void Main ( )
{
int two,count,y;
two = 2;
count=1;
System.Console.WriteLine("Multiplication Table n");
do
{
y = two * count ;
System.Console.WriteLine("2 * " + count + " = " + y) ;
count = count + 1;
}while ( count <= 10 ) ;
}
}
Exercise
 Program using do..while to print all the odd
numbers till 20
The For Statement
 Is an entry-controlled loop
 Syntax:
for(initialization;testcondition;increment)
{
Body of the loop…..
}
 All the three actions, namely initialization,
testing & incrementing, are placed in the for
statement itself.
Exercise
 Program using for loop to print multiplication
table from 2 to 5
The FOREACH Statement
 Enables to iterate elements in an array.
 General form:
foreach(type variable in expression)
{
Body of the loop
}
 The type & variable declares the iteration variable.
 During execution, iteration variable represents the array
element for which iteration is currently being performed.
 in is a keyword.
Example
using System;
class ForeachTest
{
public static void Main()
{
int[] arryInt={11,22,33,44};
foreach(int m in arryInt)
{
Console.Write(" " + m);
}
Console.WriteLine();
}
}
Jumps in Loops
 C# permits a jump from one statement to the end or
beginning of a loop as well as jump out of a loop.
 Jumping Out of a loop
 An early exit from a loop can be accomplished by using the
break & goto statements.
 Using break statement the loop is immediately exited and
the program continues with the statement immediately
following the loop.
 Skipping a Part of a Loop
 The continue statement causes the loop to continue with
the next iteration after skipping any statements in the
between.
while(……….)
{
………………….
……………………
if (condition)
break;
……………..
……………..
}
……………..
for (……….)
{
………………
if (error)
break;
……………..
……………..
}
………………..
Exit from
loop
do
{
……………
………..
if (condition)
break;
…………..
…………..
}while (…………….)
……….
for (……………….)
{
…………
for (………..)
{
…………..
if (condition)
break;
……………
}
……………
}
Exit from
loop
Exit from
loop Exit from
loop
Exiting a loop with break statement
while (test condition)
{
…………
if (………..)
continue;
………….
………….
}
for (initialization; test condition; increment)
{
…………
if (………….)
continue;
…………
…………
}
do
{
………..
if (………..)
continue;
………….
…………..
} while (test condition);
Bypassing & Continuing in Loops
Labelled Jumps
 Used to jump a set of nested loops or to continue a loop
that is outside a current one.
 Example
Public static void Main(String a[])
{
if(a.Length==0)
goto end;
Console.WriteLine(a.Lenght);
end; //Label name
Console.WriteLine(“end”);
}
Chapter : 8
Methods in C#
Declaring Methods
 Methods are declared inside the body of a class
 General form:
modifiers type methodname(formal-parameter-list)
{
method---body
}
 Method declaration has five parts:
 Name of the method
 Type of value the method returns
 List of parameters
 Body of the method
 Method modifiers
 Example:
int Product(int x,int y)
{
int m=x*y;
return(m);
}