SlideShare a Scribd company logo
1 of 220
Introducing C#
 Is a computer-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.
 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#.
 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
 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.
 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#
 C# is a descendant of C++ which in turn is a descendant of C
as illustrated below:
C
C++
Java C# VB
Concept
Productivity
Elegance
Concept
Component
Orientation
Object
Orentation
Power
 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
 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.
 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
 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
 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
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
Understanding .NET: The C# Environment
 .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 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
 .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
.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 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
 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
Intermedia Language (IL)
Common Type System
Common Language Runtime
Execution Support Functions
Security
Garbage Collection
Class Loader
Memory Layout
 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
 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.
 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
Overview of C#
 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.
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.
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!!!”);
}
}
 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() 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 A=System.Console;
class SampleFour
{
public static void Main()
{
A.WriteLine(“Hello World!!!”);
}
}
using System;
class SampleFive
{
public static void Main()
{
string name=“PentaSoft Technologies”;
Console.WriteLine(name);
}
}
 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]);
}
}
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
}
}
using System;
class SampleEight
{
public static void Main(string[] args)
{
Console.Write(“Enter Your Name”);
string name=Console.ReadLine();
Console.WriteLine(“Hello ”+name);
}
}
using System;
class SampleNine
{
public static void Main(string[] args)
{
double x=5.0;
double y;
y=Math.Sqrt(x);
Console.WriteLine(“y = ”+y);
}
}
 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”);
}
}
 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
 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
Literals, Variables & Data Types
 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, , ”
 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
 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.
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
 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
 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
 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
 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.
 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.
 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
 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.
Operators & Expressions
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment & decrement operators
Conditional operators
Bitwise operators
Special 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
 Write a program to demonstrate use of all Arithmetic
operators.
 Relational operators are used to compare expressions.
 An expression containing a relational operator evaluate to
either true(1) or false (0).
Operator Symbol
Equal ==
Greater than >
Less Than <
Greater than or equal to >=
Less than or equal to <=
Not Equal to !=
 Write a program to demonstrate use of relational 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 ^
 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
Operator Symbol Action Examples
Increment ++ Increments the
operand by one
++x, x++
Decrement -- Decrements the
operand by one
--x, x--
 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.
 Write a program to demonstrate prefix and postfix modes.
 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;
 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
 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
 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
 Write a program to find square root of number 25
 Write a program to find minimum between two numbers 25
& 35 using Math class.
Decision Making & Branching
 Is a powerful decision making statement
 Used to control the flow of execution of statements
 General form:
if (boolean-expression)
{
statement-block;
}
statement-x;
boolean
expression
?
Statement
block
Statement-X
Next statement
False
True
Entry
Jumping
 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.
 Is an extension of if statement.
 General form:
if (boolean-expression)
{
true-block statement (s);
}
else
{
false-block statement (s);
}
statement-x;
boolean
expression
?
True-Block
Statement
Statement-X
Next statement
False
True
Entry
False-Block
Statement
 Write a program that counts total of even & odd numbers
stored in an array ‘number’.
 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;
Test
condition1
?
Statement-3
Statement-X
Next statement
True
False
Entry
Statement-1
Test
condition2
?
Statement-2
True
False
 Write a program that finds largest among 3 numbers using
nested if..else statement.
 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;
 Write a program that finds the grade of a student using else if
ladder.
 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.
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;
}
}
}
 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;
}
Decision Making & Looping
 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
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;
}
}
}
 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);
• Exit based loop
Body of the
loop
Test
cond
False
True
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 ) ;
}
}
 Program using do..while to print all the odd numbers till 20
 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.
 Program using for loop to print multiplication table from 2 to 5
 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.
using System;
class ForeachTest
{
public static void Main()
{
int[] arryInt={11,22,33,44};
foreach(int m in arryInt)
{
Console.Write(" " + m);
}
Console.WriteLine();
}
}
 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
 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”);
}
Methods in C#
 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);
}
Modifier Description
new The method hides an inherited method with the same signature.
public The method can be access from anywhere, including outside the class.
protected The method can be access from within the class to which it belongs, or a type derived from
that class.
internal The method can be accessed from within the same program.
private The method can only be accessed inside the class to which it belongs.
static The method does not operate on a specific instance of the class
virtual The method can be overridden by a derived class.
abstract A virtual method which defines the signature of the method, but doesn’t provide an
implementation.
override The method overrides an inherited virtual or abstract method.
sealed The method overrides an inherited virtual method, but cannot be overridden by any class
which inherit from this class. Must be used in conjunction with override.
extern The method is implemented externally, in a different language.
 Once method is defined, they must be activated for operations.
 Process of activating a method is known as invoking or calling
 General form:
objectname.methodname(actual-parameter-list);
using System;
class Method // class containing the method
{
// Define the Cube method
public int Cube(int x)
{
return(x*x*x);
}
}
// Client class to invoke the cube method
class MethodTest
{
public static void Main( )
{
// Creat object for invoking cube
Method M = new Method( );
// invoke the cube method
int y = M.Cube(5); //Method call
// Write the result
Console.WriteLine(y);
}
}
using System;
class StaticMethod
{
public static void Main()
{
double y = Square (2.5F); //Method Call
Console.WriteLine( y );
}
static double Square ( float x )
{
return ( x * x );
}
}
 Methods can be invoked without using an
object & dot operator.
 A method can be called using only its name by
another method of the same class.
 This is known as nesting of methods.
using System;
class Nesting
{
public void Largest ( int m, int n )
{
int large = Max ( m , n );
Console.WriteLine( large );
}
int Max ( int a, int b )
{
int x= ( a > b ) ? a : b ;
return ( x );
}
}
class NestTesting
{
public static void Main( )
{
Nesting next = new Nesting ( ) ;
next.Largest ( 100, 200 ) ;
}
}
 For managing the process of passing values & getting back the
results, C# employs four kinds of parameters.
 Value Parameters
 Reference Parameters
 Output Parameters
 Parameter Arrays
 By default, method parameters
are passed by value.
 When a method is invoked, the
value of actual parameters are
assigned to the corresponding
formal parameters.
 Any changes to formal
parameters does not affect the
actual parameters.
 There are 2 copies of variables
when passed by value.
using System;
class PassByValue
{
static void change (int m)
{
m = m+10;
}
public static void Main( )
{
int x = 100;
change (x);
Console.WriteLine("x =" +
x);
}
}
 We can force the value parameters to be
passed by reference.
 Use ref keyword.
 This does not create a new storage
location.
 It represents the same storage location
as the actual parameter.
 When a formal parameter is declared as
ref, the corresponding actual argument
in the method invocation must be
declared as ref.
 Used when we want to change the
values of variables in the calling
method.
using System;
class PassByRef
{
static void Swap ( ref int x, ref int y )
{
int temp = x;
x = y;
y = temp;
}
public static void Main( )
{
int m = 100;
int n = 200;
Console.WriteLine("Before Swapping;");
Console.WriteLine("m = " + m);
Console.WriteLine("n = " + n);
Swap (ref m , ref n );
Console.WriteLine("After Swapping;");
Console.WriteLine("m = " + m);
Console.WriteLine("n = " + n);
}
}
 Used to pass results back to the calling method.
 Declare the parameters with an out keyword.
 It does not create a new storage location.
 When a formal parameter is declared as out, the corresponding actual argument in the method invocation must also be declared as out.
using System;
class Output
{
static void Square ( int x, out int y )
{
y = x * x;
}
public static void Main( )
{
int m; //need not be initialized
Square ( 10, out m );
Console.WriteLine("m = " + m);
}
}
 We can define methods that can
handle variable number of
arguments using parameter arrays.
 Parameter arrays are declared using
the keyword params
 The parameter arrays should be a
one-dimensional arrays.
using System;
class Params
{
static void Parray (params int [ ] arr)
{
Console.Write("array elements are:");
foreach ( int i in arr)
Console.Write(" " + i);
Console.WriteLine( );
}
public static void Main( )
{
int [ ] x = { 11, 22, 33 };
Parray ( x) ; //call 1
Parray ( ) ; //call 2
Parray ( 100, 200 ) ;//call 3
}
}
 Enables us to create more than one
method with the same name, but with
the different parameter lists &
different definitions.
 Required when methods are required
to perform similar tasks but using
different input parameters.
 Example
using System;
class Overloading
{
public static void Main()
{
Console.WriteLine(add(2,3));
Console.WriteLine(add(2.6F,3.1F));
Console.WriteLine(add(312L,22L,21));
}
static int add(int a,int b)
{
return(a+b);
}
static float add(float a,float b)
{
return(a+b);
}
static long add(long a,long b,int c)
{
return(a+b+c);
}
}
Handling Arrays
 Array is a group of contiguous or related data items that
share a common name.
 A particular value is indicated by writing a number called
index number or subscript in brackets after the array name.
 Example : marks[10]
 The complete set of values is referred to as an array.
 The individual values are called elements.
 A list of items can be given one variable name using only one subscript & such a
variable is called a one-dimensional array.
 Declaration of Arrays:
 Syntax: type[] arrayname;
 Example: int[] counter;
float[] marks;
int[] x,y;
 Creation of Arrays:
 Syntax: arrayname = new type[size];
 Example: counter=new int[5];
marks=new float[4];
 Combination:
int[] counter=new int[5];
 Initialization of Arrays:
 Syntax: arrayname[subscript]=value;
 Example: marks[0]=60;
marks[1]=70;
int[] counter={10,20,30,40,50};
int len=c.Length; //Returns Length of Array
 Write a program to sort an array of 5 number taking from user
as input.
 Allows to store table of values.
 Example: v[4,5];
 Each dimension of the array is indexed from zero to its maximum size minus one.
 First index specifies the row & second index specifies the column within that row.
 Declaration: int[,] myArray;
 Creation: myArray=new int[3,4];
 Combination: int[,] myArray=new int[3,4];
 Initialization: int[,] n={{0,0,0},
{1,1,1}};
using System;
class MulTable
{
static int ROWS = 5;
static int COLUMNS = 10;
public static void Main( )
{
int[,] product =new int[ROWS,COLUMNS];
int i,j;
for (i=1; i<ROWS; i++)
{
for (j=1; j<COLUMNS; j++)
{
product[i, j] = i*j;
Console.Write(" " +product[i , j]);
}
Console.WriteLine(" ");
}
}
}
 C# treats multidimensional arrays as ‘arrays of arrays’.
 It is possible to declare two-dimensional array as follows:
 int[][] x=new int[3][]; //three rows array
 x[0]=new int[2]; //first row has two elements
 x[1]=new int[4]; //second row has four elements
 x[2]=new int[3]; //third row has three elements
 These statements create a two-dimensional array having different length
for each row.
 Also called as jagged arrays.
 Initializing: x[1][1]=10;
 In C# every array we create is automatically derived from the
System.Array class.
 Methods/properties present in this class:
Method/Property Purpose
Clear() Sets a range of array elements to empty values
CopyTo() Copies elements from source array to destination array
GetLength() Gives the number of elements in a given dimension of the
array
GetValue() Gets the value for a given index in the array
Length Gets the lengths of an array
SetValue() Sets the value for a given index in the array
Reverse() Reverses the contents of a one-dimensional array
Sort() Sorts the elements in a one-dimensional array.
using System;
class Sort
{
public static void Main( )
{
int[] x ={10,5,2,11,7};
Console.WriteLine("Before Sort");
foreach(int i in x)
Console.WriteLine(" " + i);
Console.WriteLine(" ");
Array.Sort(x);
Console.WriteLine("After Sort");
foreach(int i in x)
Console.WriteLine(" " + i);
Console.WriteLine(" ");
}
}
 Present in System.Collections namespace.
 Can store a dynamically sized array of objects.
 Has an ability to grow dynamically.
 Example:
 ArrayList city=new ArrayList(30);
 Creates city with a capacity to store 30 objects.
 Default is 16.
 Adding Elements: city.Add(“Delhi”);
city.Add(“Mumbai”);
 Removing Elements: city.RemoveAt(1);
 Modifying Capacity: city.Capacity=20;
using System;
using System.Collections;
class Sort
{
public static void Main( )
{
ArrayList city=new ArrayList();
city.Add("Delhi");
city.Add("Mumbai");
city.Add("Madras");
city.Add("Kerela");
Console.WriteLine("Capacity=" + city.Capacity);
for(int i=0;i<city.Count;i++)
Console.WriteLine(" " + city[i]);
Console.WriteLine(" ");
city.Sort();
Console.WriteLine("After Sort");
for(int i=0;i<city.Count;i++)
Console.WriteLine(" " + city[i]);
}
}
Method/Property Purpose
Add() Adds an object to a list
Clear() Removes all the elements from the list
Contains() Determines if an element is in the list
CopyTo() Copies a list to another
Insert() Inserts an elements into the list
Remove() Removes the first occurrence of an element
RemoveAt() Removes the element at the specified place
RemoveRange() Removes a range of elements
Sort() Sorts the elements
Capacity Gets or sets the number of elements in the list
Count Gets the number of elements currently in the list.
Manipulating Strings
 Represents a sequence of characters
 Example : string s1=“abc”’;
 Copying String:
string s2=s1;
string s2=String.Copy(s1);
 Concatenating String:
string s3=s1+s2;
string s3=string.Concat(s1,s2);
 Reading from keyboard:
string s=Console.ReadLine();
 Conversion:
int num=111;
string s=num.ToString();
 Verbatim Strings: Starts with @ symbol. Tells the compiler to
use string as verbatim string even if it includes escapes
characters.
String s1=@”EGBCSharpString.cs”;tim
 String objects are immutable.
 Thus we cannot modify the characters contained in them.
 However we can produce a modified version of a string
using built in operations.
 Methods:
Compare(), Concat(), Copy(), Equals(), Insert(), Join(),
Replace(), Split(), ToLower(), ToUpper(), Trim(), TrimStart(),
TrimEnd().
using System;
class demo
{
public static void Main()
{
string s1="Lean";
string s2=s1.Insert(3,"r");
string s3=s2.Insert(5,"er");
string s4="Learner";
string s5=s4.Substring(4);
Console.WriteLine(s2);
Console.WriteLine(s3);
if(s3.Equals(s4))
Console.WriteLine("Two Strings are Equal");
Console.WriteLine("Substring="+s5);
}
}
 They cab be modified using StringBuilder class.
 Can grow dynamically.
 Also known as dynamic strings.
 Example:
StringBuilder s=new StringBuilder(“abc”);
 Methods:
Append(), Insert(), Remove(), Replace()
 Property:
Capacity, Length, [ ]
using System;
using System.Text;
class StringBuild
{
public static void Main()
{
StringBuilder s=new StringBuilder("Object ");
Console.WriteLine("Original="+s);
Console.WriteLine("Length="+s.Length);
s.Append("Language");
Console.WriteLine("Append="+s);
s.Insert(6," Oriented ");
Console.WriteLine("Inserted="+s);
}
}
 Provides a powerful tool for searching & manipulating a
large text.
 Used to:
 Locate substrings & return them
 Modify one or more substrings & return them
 Identify substrings that begin with or end with a pattern of
characters
 Find all words that begin with a group of characters and end
with some other characters
 A regular expression (also known as pattern string) is a
string containing two types of characters,
 Literals
 Metacharacters
 Literals are characters that we wish to search & match in
the text
 Metacharacters are special types of characters that give
commands to the regular expression parser.
 Examples of Regular Expression:
Expression Meaning
“bm” Any Word Beginning with m
“erb” Any word Ending with er
“bmS*erb” Any word beginning with m and ending with er
“|,” Any word separated by spaces or comma
System.Text.RegularExpressions supports a number of classes that can be
used for searching, matching & modifying a text document.
using System;
using System.Text; //for StringBuilder class
using System.Text.RegularExpressions; //for Regex class
class RegexTest
{
public static void Main ( )
{
string str;
str = "Amar, Akbar, Antony are friends!";
Regex reg = new Regex (" |, ");
StringBuilder sb = new StringBuilder( );
int count = 1;
foreach(string sub in reg.Split(str))
{
sb.AppendFormat("{0}: {1}n", count++, sub);
}
Console.WriteLine(sb);
}
}
Structures & Enumerations
 We can create our own value types using structures.
 Used to pack data of different types.
 Syntax: Define Structure
struct struct-name
{
datamember1;
datamember2;
…….
}
 The variables inside struct are called as members or fields or elements.
 Creating variables of new type:
struct-name variablename;
or
struct-name variablename = new struct-name();
 Assigning values to Members:
variablename.datamember1=value;
 Struct data members are private by default & hence declare them as public.
using System;
struct Item
{
public string name;
public int code;
public double price;
}
class StructTest
{
public static void Main( )
{
Item fan;
fan.name = "Bajaj";
fan.code = 123;
fan.price = 1576.50;
Console.WriteLine("Fan name: " + fan.name);
Console.WriteLine("Fan code: " + fan.code);
Console.WriteLine("Fan cost: " + fan.price);
}
}
 We can also assign values to data members using constructors.
 A constructor is a method which is used to set values of data members at the time of declaration.
struct Number
{
int number;
public Number (int value)
{
number=value;
}
}
 The constructor is invoked as follows:
Number num=new Number(190);
using System;
struct Rectangle
{
int a, b;
public Rectangle ( int x, int y ) //constructor
{
a = x;
b = y;
}
public int Area( ) //a method
{
return ( a * b );
}
public void Display ( ) //another method
{
Console .WriteLine("Area = " + Area( ) );
}
}
class TestRectangle
{
public static void Main ( )
{
Rectangle rect = new Rectangle ( 10, 20 );
rect.Display ( ); //invoking Display ( ) method
}
}
Category Classes Structs
Data Type Reference type & stored on
heap
Value Type & stored on stock
Inheritance Support Inheritance Do Not Support Inheritance
Default Values Default value of a class type is
null
Default value is the value
produced by ‘zeroing out’ the
fields of struct
Field Initialization Permit initialization of instance
fields
Do Not
Constructors Permit declaration of
parameterless constructors
Do Not
Destructors Supported Not Supported
Assignment Copies the referennce Copies the value
 Is a user defined integer type.
 Provides ways for attaching names to numbers.
 Enum keyword automatically enumerates list of words by
assigning them values 0,1,2 & so on.
 General Form:
enum Shape
{
Circle,
Square,
Triangle
}
Here Circle has value 0, Square has value 1 & Triangle has
value 2.
using System;
class Area
{
public enum Shape {Circle,Square}
public void AreaShape ( int x, Shape shape)
{
double area;
switch (shape)
{
case Shape.Circle:
area = Math.PI * x * x;
Console.WriteLine("Circle Area = "+area);
break;
case Shape.Square:
area = x * x ;
Console.WriteLine("Square Area = " +area);
break;
default:
Console.WriteLine("Invalid Input");
break;
}
}
}
class EnumTest
{
public static void Main( )
{
Area area = new Area ( );
area.AreaShape ( 15, Area.Shape.Circle);
area.AreaShape ( 15, Area.Shape.Square);
area.AreaShape ( 15, (Area.Shape) 1 );
area.AreaShape ( 15, (Area.Shape) 10 );
}
}
Classes & Objects
 C# is a true object oriented language.
 We create objects of a have class that have state & behavior.
 Object oriented language employ 3 core principles:
 Encapsulation
 Inheritance
 Polymorphism.
 OOP provides data hiding
 A class may be designed to hide its members from outside
accessibility.
 This is achieved using access specifiers.
 In C# all members have private access by default.
Modifier Accessibility Control
private Member is accessible only from the class containing the member.
public Member is accessible from anywhere outside the class as well.
Also accessible in derived class
protected Member is accessible only to its own class & in derived class.
internal Member is available within the assembly or component that is
being created but not to the clients of that component.
protected
internal
Available in the containing program & in the derived class
 An object in C# is a block of memory that contains space to
store all the instance variable.
 Creating an Object:
Rectangle rect; //declare
rect=new Rectangle(); //instantiate
Or
Rectangle rect=new Rectangle();
 We can create ‘n’ number of objects of a class each having a
different memory storage area.
 Accessing Class Members:
objectname.variablename;
objectname.methodname(parameter-list);
using System;
class Rectangle
{
public int length, width;
public void GetData(int x, int y)
{
length = x;
width = y;
}
public int RectArea( )
{
int area = length * width;
return (area);
}
}
class Rect
{
public static void Main()
{
int area1;
Rectangle rect1=new Rectangle();
rect1.GetData(12,10);
area1=rect1.RectArea();
Console.WriteLine("Area="+area1);
}
}
 Used to initialize an object when it is created.
 Have the same name as that of the class.
 They do not have a return type.
using System;
class Rectangle
{
public int length, width;
public Rectangle(int x, int y)
{
length = x;
width = y;
}
public int RectArea( )
{
int area = length * width;
return (area);
}
}
class Rect
{
public static void Main()
{
int area1;
Rectangle rect1=new Rectangle(12,10);
area1=rect1.RectArea();
Console.WriteLine("Area="+area1);
}
}
• Constructors with same name as of class but different no. &
name of arguments.
• Also known as polymorphism.
using System;
class Room
{
public int length, width;
public Room(int x, int y)
{
length = x;
width = y;
}
public Room(int x)
{
length = width=x;
}
public int RArea( )
{
int area = length * width;
return (area);
}
}
class Area
{
public static void Main()
{
int area1;
Room r1=new Room(12,10);
Room r2=new Room(12);
area1=r1.RArea();
Console.WriteLine("Area="+area1);
area1=r2.RArea();
Console.WriteLine("Area="+area1);
}
}
 They are common to all the
objects.
 Are accessed without using
a particular object.
 Also referred as class
variables & class methods.
 A static variable is common
to all instances of a class.
 Even methods can be
declared as static.
 Restrictions on Static
Methods:
 Can only call other static
methods.
 Can only access static
data.
 Cannot refer to this or
base in any way
using System;
class Mathopt
{
public static float mul(float x, float y)
{
return(x*y);
}
public static float divide(float x, float y)
{
return(x/y);
}
}
class MathApp
{
public static void Main()
{
float a=Mathopt.mul(10,20);
float b=Mathopt.divide(20,4);
Console.WriteLine("Multiplication="+a);
Console.WriteLine("Division="+b);
}
}
 Is called before any object of a class is created.
 Useful to do any housekeeping work that needs to be done once.
 Used to assign initial values to static data members.
 Static constructor do not have any parameters.
 Example:
class Abc
{
static Abc()
{
………
}
}
 A class can have only one static constructor
 A copy constructor creates an object by copying variables
from another object.
 Example:
public Item(Item item)
{
code=item.code;
price=item.price;
}
…………
Item item2=new Item(item1);
 Here item2 is an copy of item1.
 It is opposite to constructor.
 It is a method called when an
object is no longer required.
 The name of destructor is same
as that of class name & is
preceded by a tilde(~).
 They do not have a return type.
 They do not take arguments.
 Example:
class Fun
{
…….
~Fun()
{
…..
}
}
 C# manages memory
dynamically & uses a garbage
collector, to execute all
destructors on exit.
 This process is called
finalization.
 This refers to the object that called the method.
 Used to distinguish between local & instance variables that have the same name.
 Example:
class Integers
{
int x;
int y;
public void SetXY(int x, int y)
{
this.x=x;
this.y=y;
}
…..
…..
}
 They are the variables whose value cannot be changed during program
execution.
 Example:
public const int size=100;
 Any attempt to change the value of a constant result in compilation error.
 The const members are implicitly static.
 Const members are accessed using class name.
 Value must be set when cont is defined.
 Allows us to decide the value of
a constant member at run-time.
 Also allows to have different
constant values for different
objects of the class.
 The value of the member is set
using constructor & cannot be
modified later.
 Can be declared as either static
fields or instance fields.
 Example:
class Numbers
{
public readonly int m;
public static readonly int n;
public Numbers(int x)
{
m=x;
}
static Numbers()
{
n=100;
}
}
 In C# private data members can only be accessed using
methods of a class.
 Such methods are called as an accessor methods.
 Drawbacks of using these methods:
 We have to code them manually.
 User have to remember that they have to use accessor
methods to work with data members.
 C# provides ‘properties’ that has same capabilities as of
accessor methods.
 Using property we can access data members as if they are
public.
 Also referred to as smart fields.
using System;
class Number
{
private int number;
public int Anumber
{
get
{
return number;
}
set
{
number=value;
}
}
}
class PropertyTest
{
public static void Main()
{
Number n=new Number();
n.Anumber=20;
int m=n.Anumber;
Console.WriteLine("Number="+m
);
}
}
 Above class declares a get accessor method
(getter) & a set accessor method (setter).
 A property can omit either a get clause or a set clause.
 A property that has only a getter is called a read-only property.
 A property that has only a setter is called a write-only
property.
 Other features:
 Properties can also represent dynamic data.
 Properties are also inheritable.
 Can be used with static keyword.
 Indexers are locations indicators.
 Used to access class objects.
 An indexer looks like a property &
is written like it but with 2
differences:
 The indexer takes an index
argument & looks like an array.
 The indexer is declared using
keyword this.
 Also referred to as smart arrays.
 Difference between indexers &
properties:
 A property can be static member,
whereas an indexer is always an
instance member.
 A get accessor of a property
corresponds to a method with no
parameters, whereas for indexer
it corresponds to same formal
parameter list as the indexer.
 A set accessor of a property
corresponds to a method with a
single parameter named value,
whereas for indexer it
corresponds to same formal
parameter list as the indexer,plus
the paramter named value.
 It is an error for an indexer to
declare a local variable with the
same name as an indexer
parameter.
using System;
using System.Collections;
class MyClass
{
private string []data = new string[5];
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = “UniqueInfotech";
mc[1] = “18";
mc[2] = “Janardan Arcade";
mc[3] = “Dahanu";
mc[4] = “West";
Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc
[1],mc[2],mc[3],mc[4]);
}
}
Inheritance & Polymorphism
(IMP)
 Inheritance is a process of constructing or designing one class
from another.
 Forms of Inheritance
 Classical form
 Containment form
Feature X
Feature Y
Feature Z
Feature X
Feature Y
Feature Z
Feature P
Base Class
Derived Class
 Represents a kind of relationship between two classes.
 Example:
 Here class A is referred to as base class, parent class or super
class.
 Class B is referred to as derived class, child class or sub class.
 Also referred to as ‘is-a’ relationship.
 Example:
 Dog is-a type of animal
 Ford is-a type of car
Class A
Class B
A
B
A
C
B
A
D
C
B
A
B
C
Grandparent class
Parent class
Child class
Single Inheritance
Hierarchical
Inheritance
Multiple
Inheritance
Multilevel
Inheritance
 Also known as containership
inheritance.
 Example:
class A
{
….
}
class B
{
….
A a; //a is contained in b
}
B b;
….
 Here object a is contained in
object b.
 This relationship is referred to
as ‘has-a’ relationship.
 The outer class B which contains
the inner class A is termed the
‘parent’ class & the contained
class A is termed a ‘child’ class.
 Example:
 Car has-a radio.
 City has-a road.
 Syntax:
class subclass-name : baseclass-name
{
variable declaration;
methods declaration;
}
using System;
class Item
{
public void Company()
{
Console.WriteLine("Item Code=XYZ");
}
}
class Fan:Item
{
public void Model()
{
Console.WriteLine("Model=Classic");
}
}
class SimpleInheritance
{
public static void Main()
{
Fan f=new Fan();
f.Company();
f.Model();
}
}
 A derived class extends its direct base class. It can add new
members to those it inherits. However, it cannot change or remove
the definition of an inherited member.
 A derived class can hide an inherited member.
 A derived class can override an inherited member.
 An instance of a class contains a copy of all instance fields
declared in the class & its base class.
 Constructors and destructors are not inherited.
 Class Visibility :
 A class may be declared as:
 public: Accessible within & outside the program assembly
 internal (default): Accessible only within program assembly
 private: Accessible only within the class.
 Class Members Visibility :
 Can be declared as either:
 public
 private
 protected
 internal
 protected internal
Keyword Visibility
Containing
Classes
Derived
Classes
Containing
Program
Anywhere
Outside the program
Private Y
Protected Y Y
Internal Y Y
P.Internal Y Y Y
Public y Y y Y
 Constraints on the accessibility of members & classes when
they are used in process of inheritance:
 The direct base class of a derived class must be at least as
accessible as the derived class itself.
 Accessibility domain of a member is never larger than that of the
class containing it.
 The return type of a method must be as accessible as the method
itself.
using System;
class Room
{
public int length;
public int breadth;
public Room(int x, int y)
{
length=x;
breadth=y;
}
public int Area()
{
return(length*breadth);
}
}
class BedRoom:Room
{
int height;
public BedRoom(int x,int y,int z):base(x,y)
{
height=z;
}
public int Volume()
{
return(length*breadth*height);
}
}
class InherTest
{
public static void Main()
{
BedRoom room1=new BedRoom(10,11,12);
int area1=room1.Area();
int vol=room1.Volume();
Console.WriteLine("Area= "+area1);
Console.WriteLine("Volume= "+vol);
}
}
 Uses derived class as a super class
 Here A servers as base class for B which in turn serves as base class
for C.
 The chain ABC is known as inheritance path.
 This process may be extended to any number of levels.
 Write a program to store & display student information using
multilevel inheritance.
A
B
C
Grandparent class
Parent class
Child class
Account
Current
Fixed-Deposit
Savings
Long
Medium
Short
 Write a program to demonstrate use of hierarchical inheritance.
 In derived class we can create a method with same signature as in base
class.
 This concept is called as method overriding.
 This method can have same name, same arguments & same return type
as a method in base class.
 When the method is called, the method defined in the subclass is invoked
& executed.
 The method in base class should be specified as virtual.
 The method in base class should be specified with keyword override.
using System;
class Super
{
public int x;
public Super(int x)
{
this.x=x;
}
public virtual void Display()
{
Console.WriteLine("Super
x="+x);
}
}
class Sub:Super
{
int y;
public Sub(int x,int y) : base(x)
{
this.y=y;
}
public override void Display()
{
Console.WriteLine("Super x="+x);
Console.WriteLine("Sub y="+y);
}
}
class Test
{
public static void Main()
{
Sub s1=new Sub(100,200);
s1.Display();
}
}
 With the help of virtual & override
keywords we can hide an method declared
in a base class.
 What if the class is provided by someone
else?
 Here the base class method cannot be
declared as virtual.
 To override such method use modifier new
to tell the compiler the derived class
method “hides” the base class method.
 Example:
using System;
class Base
{
public void Display()
{
Console.WriteLine("Base Method");
}
}
class Derived:Base
{
public new void Display()
{
Console.WriteLine("Derived
Method");
}
}
class HideTest
{
public static void Main()
{
Derived d=new Derived();
d.Display();
}
}
 At times we can have one base class
& a number of different derived
classes.
 The top-most base class simply acts
as a base for others & is not useful
on its own.
 We might not want to create an
objects of such classes.
 This can be done by making the class
as abstract.
 Example:
abstract class Base
{
………
}
class Dervied:Base
{
……..
}
…….
…….
Base b1; //Error
Derived d1; //Ok
 Characteristic:
 It cannot be instantiated directly.
 It can have abstract members.
 We cannot apply a sealed modifier to
it.
 Method declaration includes the
modifier abstract.
 It is implicitly a virtual method
& does not provide any
implementation.
 An abstract method does not
have a method body.
 Example:
public abstract void Draw (int x,
int y);
 Characteristics:
1. It cannot have
implementation.
2. Its implementation must be
provided in non-abstract
derived classes by overriding
the method.
3. It can be declared only in
abstract classes.
4. It cannot take either static or
virtual modifiers.
5. An abstract definition is
permitted to override a virtual
method.
 Prevent a class from being further sub classed.
 Such classes are called sealed classes.
 Example:
sealed class AClass
{
…..
}
sealed class BClass:Someclass
{
…..
}
 Any attempt to inherit these classes will cause an error & compiler will not allow it.
 Standalone utility classes are created as sealed classes.
 When an instance method declaration includes the sealed modifier, the method is said to be a sealed
method.
 A derived class cannot override this method.
 A sealed method is used to override an inherited virtual method with the same signature.
 Example:
class A
{
public virtual void Fun()
{
……
}
}
class B: A
{
public sealed override void Fun()
{
……
}
}
 Now any derived class of B cannot further override the method Fun().
 Means ‘one name ….. many forms’.
 Polymorphism can be achieved in two ways:
Polymorphism
Inclusion
Polymorphism
Operation
Polymorphism
Using
Virtual
Methods
Using
Overloaded
Methods
 Implemented using overloaded methods & operators.
 Overloaded methods are selected for invoking by matching arguments, in
terms of number, type & order.
 This information is known to compiler at compile time.
 Also called as early binding, or static binding or static linking.
 Also known as compile time polymorphism.
 Early binding means an object is bound to its method call at compile time.
using System;
class Dog
{
}
class Cat
{
}
class Operation
{
static void Call(Dog d)
{
Console.WriteLine("Dog is
called");
}
static void Call(Cat c)
{
Console.WriteLine("Cat is
called");
}
public static void Main()
{
Dog dog=new Dog();
Cat cat=new Cat();
Call(dog);
Call(cat);
}
}
 Achieved through use of virtual functions.
 Assume class A implements virtual method M. Classes B & C are derived
from A and override method M. When B is cast to A, a call to method M
from A is dispatched to B. Similarly when C is cast to A, a call to method
M from A is dispatched to C.
 Also known as run-time polymorphism.
 Since method is linked with a particular class much later after
compilation, this process is also called late binding.
 Also known as dynamic binding as the selection of method is done
dynamically at run time.
using System;
class Maruti
{
public virtual void Display()
{
Console.WriteLine("Maruti Car");
}
}
class SX4:Maruti
{
public override void Display()
{
Console.WriteLine("SX4 Car")
}
}
class Swift:Maruti
{
public override void Display()
{
Console.WriteLine("Swift Car");
}
}
class Inclusion
{
public static void Main()
{
Maruti m=new Maruti();
m=new SX4();
m.Display();
m=new Swift();
m.Display();
}
}
Interfaces: Multiple Inheritance
 C# does not support multiple inheritance.
 A class cannot have more than one superclass.
 C# provides an approach known as interface to support the
concept of multiple inheritance.
 An interface is a class with some differences:
 All members of an interface are implicitly public & abstract.
 An interface cannot contain constant fields, constructors &
destructors.
 Its members cannot be declared static
 General Form:
interface Interfacename
{
member declarations;
}
 Like classes, interfaces can also be extended.
 That is, an interface can be sub interfaced from other interfaces.
 General Form:
interface name2:name1
{
Members of name2
}
 Note: An interface can not extend classes
using System;
interface Addition
{
int Add();
}
interface Multiplication
{
int Mul();
}
class Computation:Addition,Multiplication
{
int x,y;
public Computation(int x,int y)
{
this.x=x;
this.y=y;
}
public int Add()
{
return(x+y);
}
public int Mul()
{
return(x*y);
}
}
class InterfaceTest
{
public static void Main()
{
Computation com=new Computation(10,20);
Addition add=(Addition)com; //casting
Console.WriteLine("Sum="+add.Add());
Multiplication mul=(Multiplication)com;
Console.WriteLine("Product="+mul.Mul());
}
}
using System;
interface Area
{
double Compute(double x);
}
class Square:Area
{
public double Compute(double x)
{
return(x*x);
}
}
class Circle:Area
{
public double Compute(double x)
{
return(Math.PI*x*x);
}
}
class Interface2
{
public static void Main()
{
Square s=new Square();
Circle c=new Circle();
Area area;
area=s as Area;
Console.WriteLine("Area of
Square="+area.Compute(10.2));
area=c as Area;
Console.WriteLine("Area of
Square="+area.Compute(10.2));
}
}
 A base class of a derived class may
implement an interface.
 When an object of the derived class is
converted to the interface type, the
inheritance hierarchy is searched for a
class that directly implements the
interface.
 Example:
using System;
interface Display
{
void Print();
}
class B:Display
{
public void Print()
{
Console.WriteLine("Base
Display");
}
}
class D:B
{
public new void Print()
{
Console.WriteLine("Derived
Display");
}
}
class Interface3
{
public static void Main()
{
D d=new D();
d.Print();
Display dis=(Display)d;
dis.Print();
}
}
 It may be possible that multiple interface have a
method of a same name.
 This may create a problem when a class
implements more than one interface.
 C# supports a technique known as explicit
interface implementation, which allows a method
to specify explicitly the name of the interface it is
implementing.
 Example:
using System;
interface I1
{
void display();
}
interface I2
{
void display();
}
class C1:I1,I2
{
void I1.display()
{
Console.WriteLine("I1 Display");
}
void I2.display()
{
Console.WriteLine("I2 Display");
}
}
class Interface4
{
public static void Main()
{
C1 c=new C1();
I1 i1=(I1)c;
i1.display();
I2 i2=(I2)c;
i2.display();
}
}
 An abstract class can use an interface in the base class list.
 Here the interface methods are implemented as abstract methods.
 Example:
interface A
{
void Method();
}
abstract class B:A
{
……….
……….
public abstract void Method();
}
 Here class B does not implement the interface method; it simply redeclares as a public abstract method.
 It is the duty of the class that derives from B to override & implement the method.
Operator Overloading
 The C# operators can be defined to work with the user-defined data types
such as structs & classes.
 C# has the ability to provide the operators with a special meaning for a
data type.
 This mechanism of giving such special meaning to an operator is known
as operator overloading.
 Following is list of operators that can be overloaded.
Category Operators
1. Binary Arithmetic +,*,/,-,%
2. Unary Arithmetic +,-,++,--
3. Binary bitwise &,|,^,<<,>>
4. Unary bitwise !,~,true,false
5. Relational Operators ==,!=,>=,<,<=,>
 Following is list of operators that cannot be overloaded.
Category Operators
1. Conditional operators &&,||
2. Compound assignment +=,-=,*=,/=,%=
3. Other operators [ ],( ),=,?:,->,new,sizeof,typeof,is,as
 Operator overloading gives us syntactical convenience.
 It helps us to generate more readable code in a number of
situations. These includes:
 Financial programs.
 Mathematical or physical modeling
 Graphical programs
 Text manipulations
 General form of an operator method:
public static retval operator op(arglist)
{
Method body…..
}
using System;
class Space
{
int x,y,z;
public Space(int a,int b, int c)
{
x=a;
y=b;
z=c;
}
public void Display()
{
Console.Write(" "+x);
Console.Write(" "+y);
Console.Write(" "+z);
Console.WriteLine();
}
public static Space operator -(Space s)
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
return(s);
}
}
class SpaceTest
{
public static void Main()
{
Space s=new Space(10,-20,30);
Space q;
Console.Write("S: ");
s.Display();
q=-s;
Console.Write("Q: ");
q.Display();
}
}
using System;
class Complex
{
double x,y;
public Complex(){ }
public Complex(double real,double imag)
{
x=real;
y=imag;
}
public static Complex operator +(Complex
c1,Complex c2)
{
Complex c3=new Complex();
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return(c3);
}
public void display()
{
Console.Write(x);
Console.Write(" + j"+y);
Console.WriteLine();
}
}
class ComplexTest
{
public static void Main()
{
Complex a,b,c;
a=new Complex(2.5,3.5);
b=new Complex(1.6,2.7);
c=a+b;
c.display();
}
}
 C# supports six comparison operators that can be considered
in three pairs:
 == & !=
 > & <=
 < & >=
 The significance of pairing is two-fold:
 Within each pair, the second operator should always give exactly
the opposite result to the first.
 C# always requires us to overload the comparison operators in
pairs. That is, if we overload ==, then we must overload != also,
otherwise it is an error.
using System;
class Vector
{
int x,y,z;
public Vector(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
public static bool operator ==(Vector
v1,Vector v2)
{
if(v1.x==v2.x && v1.y==v2.y)
return(true);
else
return(false);
}
public static bool operator !=(Vector v1,Vector
v2)
{
return(!(v1==v2));
}
}
class CompareTest
{
public static void Main()
{
Vector u1=new Vector(1,2,3);
Vector u2=new Vector(1,2,3);
if(u1==u2)
Console.WriteLine("U1 is equal to U2");
else
Console.WriteLine("U1 is not equal to
U2");
}
}
Delegates & Events
(IMP)
 A delegate object is a special type of object that contains the
details of a method rather than data.
 Delegates in C# is used for two purposes:
 Callback
 Event Handling
 Dictionary meaning of delegate is “a person acting for another
person”, in C# it means a method acting for another method.
 A delegate in C# is a class type object & is used to invoke a
method that has been encapsulated into it at the time of its
creation.
 General Form:
 modifier delegate return-type delegate-name(parameters);
 Delegate is derived from System.Delegate class.
 The modifier controls the accessibility of the delegate.
 Delegate may take any of the following modifiers:
new, public, private, protected, internal.
 It is a class type & can be declared in any place where a class
definition is permitted.
 A delegate may be defined in the following places:
 Inside a class
 Outside all classes
 As the top level object in a namespace.
 The methods whose references are encapsulated into a
delegate instances are known as delegate methods (or callable
entities)
 The signature & return type of delegate methods must exactly
match the signature & return type of the delegate.
 A delegate-creation-expression is used to create a new instance of a delegate.
 General Form:
 new delegate-type(expression)
 Here the delegate-type is the name of the delegate declared earlier whose object is to
be created.
 Expression must be the method name.
 The method & the object to which a delegate refers are determined when the
delegate is instantiated.
 This remains constant for the entire lifetime of the delegate.
 It is not possible to change them, once the delegate is created.
 When a delegate is invoked, it in turn invokes the method
whose reference has been encapsulated into the delegate.
 General Form:
 delegate_object(parameter list);
 The optional parameter list provides values for the parameters pf
the method to be used.
using System;
//Delegate Declaration
delegate int ArithOp(int x,int y);
class MathOperation
{
public static int Add(int a,int b)
{
return(a+b);
}
public static int Sub(int a,int b)
{
return(a-b);
}
}
class DelegateTest
{
public static void Main()
{
ArithOp op1=new
ArithOp(MathOperation.Add);
ArithOp op2=new
ArithOp(MathOperation.Sub);
int result1=op1(3,20);
int result2=op2(40,20);
Console.WriteLine("Result1="+re
sult1);
Console.WriteLine("Result2="+re
sult2);
}
}
 It is possible for delegates to hold & invoke multiple methods.
 Such delegates are called multicast delegates.
 Also known as combinable delegates.
 They must satisfy following conditions:
 Return type of such delegate must be void.
 None of the parameters of the delegates can be declared as output
parameters, using out keyword.
 If D is a delegate & d1,d2,d3 & d4 are its instances, then the statements:
 d3=d1+d2 //refers to two methods.
 d4=d3-d2 //refers to only d1 method
using System;
delegate void MDelegate();
class DM
{
public static void Display()
{
Console.WriteLine("In Display");
}
public static void Print()
{
Console.WriteLine("In Print");
}
}
class MDelegateTest
{
public static void Main()
{
MDelegate m1=new
MDelegate(DM.Display);
MDelegate m2=new
MDelegate(DM.Print);
MDelegate m3=m1+m2;
MDelegate m4=m2+m1;
MDelegate m5=m3-m2;
m3();
m4();;
m5();
}
}
 An event is a delegate type class member that is used by the
object or class to provide a notification to other object that an
event has occurred.
 The client object can act on an event by adding an event handler
to the event.
 General Form:
 modifier event type event-name;
 Since events are based on delegates, we must first declare a
delegate and then declare an instance of the delegate using the
keyword event.
using System;
//Delegate Declaration
delegate void EDelegate(string str);
class EventClass
{
public event EDelegate Status;
public void TriggerEvent()
{
Status("Event Triggered");
}
}
class EventTest
{
public static void Main()
{
EventClass ec=new
EventClass();
EventTest et=new
EventTest();
ec.Status+= new
EDelegate(et.EventCatch);
ec.TriggerEvent();
}
public void EventCatch(string str)
{
Console.WriteLine(str);
}
}
Managing Console I/O Operations
 The methods for reading & writing to the console are
provided by the System.Console class.
 This class gives us access to the standard input, standard
output & standard error streams:
Stream Object Represents
Console.In Standard Input
Console.Out Standard Output
Console.Error Standard Error
 Supports two methods for obtaining input from the keyboard.
 Read(): Returns a single character as int.
 ReadLine(): Returns a string containing a line of text.
 Supports two methods for writing to the console.
 Write(): Outputs one or more values to the screen without a new
line character.
 WriteLine(): Outputs one or more values to the screen but adds a
new line character at the end of the output.
 Write a program in C# to print the following output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
 Use overloaded WriteLine()
method.
 General Form:
 Console.WriteLine(format-string,
v1, v2, ….);
 Format String contains both
static text & markers which
indicate
 Where the values are to be printed.
 How the values are to be formatted.
 Example
 Console.WriteLine(“Sum of {0}
and {1} is {2}”,a,b,c);
 We can also specify a width for the
value using the format:
 { n , w }
 n is the index number
 w is the width for the value
 Example:
int a=45;
int b=976;
int c=a+b;
Console.WriteLine(“{0,5n+{1,5}n
} ------- n{2,5}”,a,b,c);
4 5
+ 9 7 6
-----------
1 0 2 1
programming in c#.ppt

More Related Content

Similar to programming in c#.ppt

DotNet Fundamentals
DotNet FundamentalsDotNet Fundamentals
DotNet FundamentalsMajdi SAIBI
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics PresentationSudhakar Sharma
 
.Net framework
.Net framework.Net framework
.Net frameworkRaghu nath
 
Advance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptxAdvance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptxpercivalfernandez3
 
Advance C# Programming Part 1.pdf
Advance C# Programming Part 1.pdfAdvance C# Programming Part 1.pdf
Advance C# Programming Part 1.pdfpercivalfernandez2
 
1-.NET Introduction.pptx
1-.NET Introduction.pptx1-.NET Introduction.pptx
1-.NET Introduction.pptxRKAggarwal6
 
Unit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdfUnit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdfUjwala Junghare
 
Overview of .Net Framework
Overview of .Net FrameworkOverview of .Net Framework
Overview of .Net FrameworkNeha Singh
 
Reasons Why .NET framework is Most Demanding in 2023?
Reasons Why .NET framework is Most Demanding in 2023?Reasons Why .NET framework is Most Demanding in 2023?
Reasons Why .NET framework is Most Demanding in 2023?Polyxer Systems
 
1 get started with c#
1   get started with c#1   get started with c#
1 get started with c#Tuan Ngo
 
.Net framework vs .net core a complete comparison
.Net framework vs .net core  a complete comparison.Net framework vs .net core  a complete comparison
.Net framework vs .net core a complete comparisonKaty Slemon
 
Net framework
Net frameworkNet framework
Net frameworkjhsri
 

Similar to programming in c#.ppt (20)

C# Introduction brief
C# Introduction briefC# Introduction brief
C# Introduction brief
 
Characteristics of c#
Characteristics of c#Characteristics of c#
Characteristics of c#
 
DotNet Fundamentals
DotNet FundamentalsDotNet Fundamentals
DotNet Fundamentals
 
C# chap 1
C# chap 1C# chap 1
C# chap 1
 
Dotnet Basics Presentation
Dotnet Basics PresentationDotnet Basics Presentation
Dotnet Basics Presentation
 
.Net framework
.Net framework.Net framework
.Net framework
 
Advance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptxAdvance C# Programming Part 1.pptx
Advance C# Programming Part 1.pptx
 
Vb.net class notes
Vb.net class notesVb.net class notes
Vb.net class notes
 
C#.ppt
C#.pptC#.ppt
C#.ppt
 
Advance C# Programming Part 1.pdf
Advance C# Programming Part 1.pdfAdvance C# Programming Part 1.pdf
Advance C# Programming Part 1.pdf
 
1-.NET Introduction.pptx
1-.NET Introduction.pptx1-.NET Introduction.pptx
1-.NET Introduction.pptx
 
Unit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdfUnit I- Introduction to .NET Framework.pdf
Unit I- Introduction to .NET Framework.pdf
 
Overview of .Net Framework
Overview of .Net FrameworkOverview of .Net Framework
Overview of .Net Framework
 
Presentation1
Presentation1Presentation1
Presentation1
 
Asp.net new
Asp.net newAsp.net new
Asp.net new
 
C#.NET
C#.NETC#.NET
C#.NET
 
Reasons Why .NET framework is Most Demanding in 2023?
Reasons Why .NET framework is Most Demanding in 2023?Reasons Why .NET framework is Most Demanding in 2023?
Reasons Why .NET framework is Most Demanding in 2023?
 
1 get started with c#
1   get started with c#1   get started with c#
1 get started with c#
 
.Net framework vs .net core a complete comparison
.Net framework vs .net core  a complete comparison.Net framework vs .net core  a complete comparison
.Net framework vs .net core a complete comparison
 
Net framework
Net frameworkNet framework
Net framework
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 

programming in c#.ppt

  • 1.
  • 3.  Is a computer-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.
  • 4.  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#.
  • 5.  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
  • 6.  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.
  • 7.  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#
  • 8.  C# is a descendant of C++ which in turn is a descendant of C as illustrated below: C C++ Java C# VB Concept Productivity Elegance Concept Component Orientation Object Orentation Power
  • 9.  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
  • 10.  Object-Oriented  C# is truly object-oriented. It supports:  Encapsulation  Inheritance  Polymorphism  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
  • 11.  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.
  • 12.  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
  • 13.  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
  • 14.  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
  • 15. 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
  • 16. Understanding .NET: The C# Environment
  • 17.  .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.
  • 18.  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
  • 19.  .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
  • 20. .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
  • 21.  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
  • 22.  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
  • 23. Intermedia Language (IL) Common Type System Common Language Runtime Execution Support Functions Security Garbage Collection Class Loader Memory Layout
  • 24.  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
  • 25.  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.
  • 26.  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
  • 28.  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.
  • 29. 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.
  • 30. 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!!!”); } }
  • 31.  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 (/* ….. ….. */)
  • 32.  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.
  • 33. using A=System.Console; class SampleFour { public static void Main() { A.WriteLine(“Hello World!!!”); } }
  • 34. using System; class SampleFive { public static void Main() { string name=“PentaSoft Technologies”; Console.WriteLine(name); } }
  • 35.  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]); } }
  • 36. 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 } }
  • 37. using System; class SampleEight { public static void Main(string[] args) { Console.Write(“Enter Your Name”); string name=Console.ReadLine(); Console.WriteLine(“Hello ”+name); } }
  • 38. using System; class SampleNine { public static void Main(string[] args) { double x=5.0; double y; y=Math.Sqrt(x); Console.WriteLine(“y = ”+y); } }
  • 39.  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”); } }
  • 40.  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
  • 41.  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
  • 42. Literals, Variables & Data Types
  • 43.  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, , ”
  • 44.  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
  • 45.  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.
  • 46. 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
  • 47.  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
  • 48.  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
  • 49.  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
  • 50.  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.
  • 51.  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.
  • 52.  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
  • 53.  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.
  • 55. Arithmetic operators Relational operators Logical operators Assignment operators Increment & decrement operators Conditional operators Bitwise operators Special operators
  • 56. 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
  • 57.  Write a program to demonstrate use of all Arithmetic operators.
  • 58.  Relational operators are used to compare expressions.  An expression containing a relational operator evaluate to either true(1) or false (0).
  • 59. Operator Symbol Equal == Greater than > Less Than < Greater than or equal to >= Less than or equal to <= Not Equal to !=
  • 60.  Write a program to demonstrate use of relational operators.
  • 61.  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 ^
  • 62.  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
  • 63. Operator Symbol Action Examples Increment ++ Increments the operand by one ++x, x++ Decrement -- Decrements the operand by one --x, x--
  • 64.  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.
  • 65.  Write a program to demonstrate prefix and postfix modes.
  • 66.  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;
  • 67.  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
  • 68.  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
  • 69.  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
  • 70.  Write a program to find square root of number 25  Write a program to find minimum between two numbers 25 & 35 using Math class.
  • 71. Decision Making & Branching
  • 72.  Is a powerful decision making statement  Used to control the flow of execution of statements  General form: if (boolean-expression) { statement-block; } statement-x;
  • 74.  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.
  • 75.  Is an extension of if statement.  General form: if (boolean-expression) { true-block statement (s); } else { false-block statement (s); } statement-x;
  • 77.  Write a program that counts total of even & odd numbers stored in an array ‘number’.
  • 78.  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;
  • 80.  Write a program that finds largest among 3 numbers using nested if..else statement.
  • 81.  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;
  • 82.  Write a program that finds the grade of a student using else if ladder.
  • 83.  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.
  • 84. 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; } } }
  • 85.  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; }
  • 86. Decision Making & Looping
  • 87.  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
  • 88. 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; } } }
  • 89.  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); • Exit based loop Body of the loop Test cond False True
  • 90. 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 ) ; } }
  • 91.  Program using do..while to print all the odd numbers till 20
  • 92.  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.
  • 93.  Program using for loop to print multiplication table from 2 to 5
  • 94.  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.
  • 95. using System; class ForeachTest { public static void Main() { int[] arryInt={11,22,33,44}; foreach(int m in arryInt) { Console.Write(" " + m); } Console.WriteLine(); } }
  • 96.  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.
  • 97. 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
  • 98. while (test condition) { ………… if (………..) continue; …………. …………. } for (initialization; test condition; increment) { ………… if (………….) continue; ………… ………… } do { ……….. if (………..) continue; …………. ………….. } while (test condition); Bypassing & Continuing in Loops
  • 99.  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”); }
  • 101.  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); }
  • 102. Modifier Description new The method hides an inherited method with the same signature. public The method can be access from anywhere, including outside the class. protected The method can be access from within the class to which it belongs, or a type derived from that class. internal The method can be accessed from within the same program. private The method can only be accessed inside the class to which it belongs. static The method does not operate on a specific instance of the class virtual The method can be overridden by a derived class. abstract A virtual method which defines the signature of the method, but doesn’t provide an implementation. override The method overrides an inherited virtual or abstract method. sealed The method overrides an inherited virtual method, but cannot be overridden by any class which inherit from this class. Must be used in conjunction with override. extern The method is implemented externally, in a different language.
  • 103.  Once method is defined, they must be activated for operations.  Process of activating a method is known as invoking or calling  General form: objectname.methodname(actual-parameter-list);
  • 104. using System; class Method // class containing the method { // Define the Cube method public int Cube(int x) { return(x*x*x); } } // Client class to invoke the cube method class MethodTest { public static void Main( ) { // Creat object for invoking cube Method M = new Method( ); // invoke the cube method int y = M.Cube(5); //Method call // Write the result Console.WriteLine(y); } }
  • 105. using System; class StaticMethod { public static void Main() { double y = Square (2.5F); //Method Call Console.WriteLine( y ); } static double Square ( float x ) { return ( x * x ); } }
  • 106.  Methods can be invoked without using an object & dot operator.  A method can be called using only its name by another method of the same class.  This is known as nesting of methods. using System; class Nesting { public void Largest ( int m, int n ) { int large = Max ( m , n ); Console.WriteLine( large ); } int Max ( int a, int b ) { int x= ( a > b ) ? a : b ; return ( x ); } } class NestTesting { public static void Main( ) { Nesting next = new Nesting ( ) ; next.Largest ( 100, 200 ) ; } }
  • 107.  For managing the process of passing values & getting back the results, C# employs four kinds of parameters.  Value Parameters  Reference Parameters  Output Parameters  Parameter Arrays
  • 108.  By default, method parameters are passed by value.  When a method is invoked, the value of actual parameters are assigned to the corresponding formal parameters.  Any changes to formal parameters does not affect the actual parameters.  There are 2 copies of variables when passed by value. using System; class PassByValue { static void change (int m) { m = m+10; } public static void Main( ) { int x = 100; change (x); Console.WriteLine("x =" + x); } }
  • 109.  We can force the value parameters to be passed by reference.  Use ref keyword.  This does not create a new storage location.  It represents the same storage location as the actual parameter.  When a formal parameter is declared as ref, the corresponding actual argument in the method invocation must be declared as ref.  Used when we want to change the values of variables in the calling method. using System; class PassByRef { static void Swap ( ref int x, ref int y ) { int temp = x; x = y; y = temp; } public static void Main( ) { int m = 100; int n = 200; Console.WriteLine("Before Swapping;"); Console.WriteLine("m = " + m); Console.WriteLine("n = " + n); Swap (ref m , ref n ); Console.WriteLine("After Swapping;"); Console.WriteLine("m = " + m); Console.WriteLine("n = " + n); } }
  • 110.  Used to pass results back to the calling method.  Declare the parameters with an out keyword.  It does not create a new storage location.  When a formal parameter is declared as out, the corresponding actual argument in the method invocation must also be declared as out. using System; class Output { static void Square ( int x, out int y ) { y = x * x; } public static void Main( ) { int m; //need not be initialized Square ( 10, out m ); Console.WriteLine("m = " + m); } }
  • 111.  We can define methods that can handle variable number of arguments using parameter arrays.  Parameter arrays are declared using the keyword params  The parameter arrays should be a one-dimensional arrays. using System; class Params { static void Parray (params int [ ] arr) { Console.Write("array elements are:"); foreach ( int i in arr) Console.Write(" " + i); Console.WriteLine( ); } public static void Main( ) { int [ ] x = { 11, 22, 33 }; Parray ( x) ; //call 1 Parray ( ) ; //call 2 Parray ( 100, 200 ) ;//call 3 } }
  • 112.  Enables us to create more than one method with the same name, but with the different parameter lists & different definitions.  Required when methods are required to perform similar tasks but using different input parameters.  Example using System; class Overloading { public static void Main() { Console.WriteLine(add(2,3)); Console.WriteLine(add(2.6F,3.1F)); Console.WriteLine(add(312L,22L,21)); } static int add(int a,int b) { return(a+b); } static float add(float a,float b) { return(a+b); } static long add(long a,long b,int c) { return(a+b+c); } }
  • 114.  Array is a group of contiguous or related data items that share a common name.  A particular value is indicated by writing a number called index number or subscript in brackets after the array name.  Example : marks[10]  The complete set of values is referred to as an array.  The individual values are called elements.
  • 115.  A list of items can be given one variable name using only one subscript & such a variable is called a one-dimensional array.  Declaration of Arrays:  Syntax: type[] arrayname;  Example: int[] counter; float[] marks; int[] x,y;  Creation of Arrays:  Syntax: arrayname = new type[size];  Example: counter=new int[5]; marks=new float[4];  Combination: int[] counter=new int[5];  Initialization of Arrays:  Syntax: arrayname[subscript]=value;  Example: marks[0]=60; marks[1]=70; int[] counter={10,20,30,40,50}; int len=c.Length; //Returns Length of Array
  • 116.  Write a program to sort an array of 5 number taking from user as input.
  • 117.  Allows to store table of values.  Example: v[4,5];  Each dimension of the array is indexed from zero to its maximum size minus one.  First index specifies the row & second index specifies the column within that row.  Declaration: int[,] myArray;  Creation: myArray=new int[3,4];  Combination: int[,] myArray=new int[3,4];  Initialization: int[,] n={{0,0,0}, {1,1,1}};
  • 118. using System; class MulTable { static int ROWS = 5; static int COLUMNS = 10; public static void Main( ) { int[,] product =new int[ROWS,COLUMNS]; int i,j; for (i=1; i<ROWS; i++) { for (j=1; j<COLUMNS; j++) { product[i, j] = i*j; Console.Write(" " +product[i , j]); } Console.WriteLine(" "); } } }
  • 119.  C# treats multidimensional arrays as ‘arrays of arrays’.  It is possible to declare two-dimensional array as follows:  int[][] x=new int[3][]; //three rows array  x[0]=new int[2]; //first row has two elements  x[1]=new int[4]; //second row has four elements  x[2]=new int[3]; //third row has three elements  These statements create a two-dimensional array having different length for each row.  Also called as jagged arrays.  Initializing: x[1][1]=10;
  • 120.  In C# every array we create is automatically derived from the System.Array class.  Methods/properties present in this class: Method/Property Purpose Clear() Sets a range of array elements to empty values CopyTo() Copies elements from source array to destination array GetLength() Gives the number of elements in a given dimension of the array GetValue() Gets the value for a given index in the array Length Gets the lengths of an array SetValue() Sets the value for a given index in the array Reverse() Reverses the contents of a one-dimensional array Sort() Sorts the elements in a one-dimensional array.
  • 121. using System; class Sort { public static void Main( ) { int[] x ={10,5,2,11,7}; Console.WriteLine("Before Sort"); foreach(int i in x) Console.WriteLine(" " + i); Console.WriteLine(" "); Array.Sort(x); Console.WriteLine("After Sort"); foreach(int i in x) Console.WriteLine(" " + i); Console.WriteLine(" "); } }
  • 122.  Present in System.Collections namespace.  Can store a dynamically sized array of objects.  Has an ability to grow dynamically.  Example:  ArrayList city=new ArrayList(30);  Creates city with a capacity to store 30 objects.  Default is 16.  Adding Elements: city.Add(“Delhi”); city.Add(“Mumbai”);  Removing Elements: city.RemoveAt(1);  Modifying Capacity: city.Capacity=20;
  • 123. using System; using System.Collections; class Sort { public static void Main( ) { ArrayList city=new ArrayList(); city.Add("Delhi"); city.Add("Mumbai"); city.Add("Madras"); city.Add("Kerela"); Console.WriteLine("Capacity=" + city.Capacity); for(int i=0;i<city.Count;i++) Console.WriteLine(" " + city[i]); Console.WriteLine(" "); city.Sort(); Console.WriteLine("After Sort"); for(int i=0;i<city.Count;i++) Console.WriteLine(" " + city[i]); } }
  • 124. Method/Property Purpose Add() Adds an object to a list Clear() Removes all the elements from the list Contains() Determines if an element is in the list CopyTo() Copies a list to another Insert() Inserts an elements into the list Remove() Removes the first occurrence of an element RemoveAt() Removes the element at the specified place RemoveRange() Removes a range of elements Sort() Sorts the elements Capacity Gets or sets the number of elements in the list Count Gets the number of elements currently in the list.
  • 126.  Represents a sequence of characters  Example : string s1=“abc”’;  Copying String: string s2=s1; string s2=String.Copy(s1);  Concatenating String: string s3=s1+s2; string s3=string.Concat(s1,s2);  Reading from keyboard: string s=Console.ReadLine();  Conversion: int num=111; string s=num.ToString();  Verbatim Strings: Starts with @ symbol. Tells the compiler to use string as verbatim string even if it includes escapes characters. String s1=@”EGBCSharpString.cs”;tim
  • 127.  String objects are immutable.  Thus we cannot modify the characters contained in them.  However we can produce a modified version of a string using built in operations.  Methods: Compare(), Concat(), Copy(), Equals(), Insert(), Join(), Replace(), Split(), ToLower(), ToUpper(), Trim(), TrimStart(), TrimEnd().
  • 128. using System; class demo { public static void Main() { string s1="Lean"; string s2=s1.Insert(3,"r"); string s3=s2.Insert(5,"er"); string s4="Learner"; string s5=s4.Substring(4); Console.WriteLine(s2); Console.WriteLine(s3); if(s3.Equals(s4)) Console.WriteLine("Two Strings are Equal"); Console.WriteLine("Substring="+s5); } }
  • 129.  They cab be modified using StringBuilder class.  Can grow dynamically.  Also known as dynamic strings.  Example: StringBuilder s=new StringBuilder(“abc”);  Methods: Append(), Insert(), Remove(), Replace()  Property: Capacity, Length, [ ]
  • 130. using System; using System.Text; class StringBuild { public static void Main() { StringBuilder s=new StringBuilder("Object "); Console.WriteLine("Original="+s); Console.WriteLine("Length="+s.Length); s.Append("Language"); Console.WriteLine("Append="+s); s.Insert(6," Oriented "); Console.WriteLine("Inserted="+s); } }
  • 131.  Provides a powerful tool for searching & manipulating a large text.  Used to:  Locate substrings & return them  Modify one or more substrings & return them  Identify substrings that begin with or end with a pattern of characters  Find all words that begin with a group of characters and end with some other characters  A regular expression (also known as pattern string) is a string containing two types of characters,  Literals  Metacharacters  Literals are characters that we wish to search & match in the text  Metacharacters are special types of characters that give commands to the regular expression parser.
  • 132.  Examples of Regular Expression: Expression Meaning “bm” Any Word Beginning with m “erb” Any word Ending with er “bmS*erb” Any word beginning with m and ending with er “|,” Any word separated by spaces or comma System.Text.RegularExpressions supports a number of classes that can be used for searching, matching & modifying a text document.
  • 133. using System; using System.Text; //for StringBuilder class using System.Text.RegularExpressions; //for Regex class class RegexTest { public static void Main ( ) { string str; str = "Amar, Akbar, Antony are friends!"; Regex reg = new Regex (" |, "); StringBuilder sb = new StringBuilder( ); int count = 1; foreach(string sub in reg.Split(str)) { sb.AppendFormat("{0}: {1}n", count++, sub); } Console.WriteLine(sb); } }
  • 135.  We can create our own value types using structures.  Used to pack data of different types.  Syntax: Define Structure struct struct-name { datamember1; datamember2; ……. }  The variables inside struct are called as members or fields or elements.  Creating variables of new type: struct-name variablename; or struct-name variablename = new struct-name();  Assigning values to Members: variablename.datamember1=value;  Struct data members are private by default & hence declare them as public.
  • 136. using System; struct Item { public string name; public int code; public double price; } class StructTest { public static void Main( ) { Item fan; fan.name = "Bajaj"; fan.code = 123; fan.price = 1576.50; Console.WriteLine("Fan name: " + fan.name); Console.WriteLine("Fan code: " + fan.code); Console.WriteLine("Fan cost: " + fan.price); } }
  • 137.  We can also assign values to data members using constructors.  A constructor is a method which is used to set values of data members at the time of declaration. struct Number { int number; public Number (int value) { number=value; } }  The constructor is invoked as follows: Number num=new Number(190);
  • 138. using System; struct Rectangle { int a, b; public Rectangle ( int x, int y ) //constructor { a = x; b = y; } public int Area( ) //a method { return ( a * b ); } public void Display ( ) //another method { Console .WriteLine("Area = " + Area( ) ); } } class TestRectangle { public static void Main ( ) { Rectangle rect = new Rectangle ( 10, 20 ); rect.Display ( ); //invoking Display ( ) method } }
  • 139. Category Classes Structs Data Type Reference type & stored on heap Value Type & stored on stock Inheritance Support Inheritance Do Not Support Inheritance Default Values Default value of a class type is null Default value is the value produced by ‘zeroing out’ the fields of struct Field Initialization Permit initialization of instance fields Do Not Constructors Permit declaration of parameterless constructors Do Not Destructors Supported Not Supported Assignment Copies the referennce Copies the value
  • 140.  Is a user defined integer type.  Provides ways for attaching names to numbers.  Enum keyword automatically enumerates list of words by assigning them values 0,1,2 & so on.  General Form: enum Shape { Circle, Square, Triangle } Here Circle has value 0, Square has value 1 & Triangle has value 2.
  • 141. using System; class Area { public enum Shape {Circle,Square} public void AreaShape ( int x, Shape shape) { double area; switch (shape) { case Shape.Circle: area = Math.PI * x * x; Console.WriteLine("Circle Area = "+area); break; case Shape.Square: area = x * x ; Console.WriteLine("Square Area = " +area); break; default: Console.WriteLine("Invalid Input"); break; } } } class EnumTest { public static void Main( ) { Area area = new Area ( ); area.AreaShape ( 15, Area.Shape.Circle); area.AreaShape ( 15, Area.Shape.Square); area.AreaShape ( 15, (Area.Shape) 1 ); area.AreaShape ( 15, (Area.Shape) 10 ); } }
  • 143.  C# is a true object oriented language.  We create objects of a have class that have state & behavior.  Object oriented language employ 3 core principles:  Encapsulation  Inheritance  Polymorphism.
  • 144.  OOP provides data hiding  A class may be designed to hide its members from outside accessibility.  This is achieved using access specifiers.  In C# all members have private access by default. Modifier Accessibility Control private Member is accessible only from the class containing the member. public Member is accessible from anywhere outside the class as well. Also accessible in derived class protected Member is accessible only to its own class & in derived class. internal Member is available within the assembly or component that is being created but not to the clients of that component. protected internal Available in the containing program & in the derived class
  • 145.  An object in C# is a block of memory that contains space to store all the instance variable.  Creating an Object: Rectangle rect; //declare rect=new Rectangle(); //instantiate Or Rectangle rect=new Rectangle();  We can create ‘n’ number of objects of a class each having a different memory storage area.  Accessing Class Members: objectname.variablename; objectname.methodname(parameter-list);
  • 146. using System; class Rectangle { public int length, width; public void GetData(int x, int y) { length = x; width = y; } public int RectArea( ) { int area = length * width; return (area); } } class Rect { public static void Main() { int area1; Rectangle rect1=new Rectangle(); rect1.GetData(12,10); area1=rect1.RectArea(); Console.WriteLine("Area="+area1); } }
  • 147.  Used to initialize an object when it is created.  Have the same name as that of the class.  They do not have a return type. using System; class Rectangle { public int length, width; public Rectangle(int x, int y) { length = x; width = y; } public int RectArea( ) { int area = length * width; return (area); } } class Rect { public static void Main() { int area1; Rectangle rect1=new Rectangle(12,10); area1=rect1.RectArea(); Console.WriteLine("Area="+area1); } }
  • 148. • Constructors with same name as of class but different no. & name of arguments. • Also known as polymorphism. using System; class Room { public int length, width; public Room(int x, int y) { length = x; width = y; } public Room(int x) { length = width=x; } public int RArea( ) { int area = length * width; return (area); } } class Area { public static void Main() { int area1; Room r1=new Room(12,10); Room r2=new Room(12); area1=r1.RArea(); Console.WriteLine("Area="+area1); area1=r2.RArea(); Console.WriteLine("Area="+area1); } }
  • 149.  They are common to all the objects.  Are accessed without using a particular object.  Also referred as class variables & class methods.  A static variable is common to all instances of a class.  Even methods can be declared as static.  Restrictions on Static Methods:  Can only call other static methods.  Can only access static data.  Cannot refer to this or base in any way
  • 150. using System; class Mathopt { public static float mul(float x, float y) { return(x*y); } public static float divide(float x, float y) { return(x/y); } } class MathApp { public static void Main() { float a=Mathopt.mul(10,20); float b=Mathopt.divide(20,4); Console.WriteLine("Multiplication="+a); Console.WriteLine("Division="+b); } }
  • 151.  Is called before any object of a class is created.  Useful to do any housekeeping work that needs to be done once.  Used to assign initial values to static data members.  Static constructor do not have any parameters.  Example: class Abc { static Abc() { ……… } }  A class can have only one static constructor
  • 152.  A copy constructor creates an object by copying variables from another object.  Example: public Item(Item item) { code=item.code; price=item.price; } ………… Item item2=new Item(item1);  Here item2 is an copy of item1.
  • 153.  It is opposite to constructor.  It is a method called when an object is no longer required.  The name of destructor is same as that of class name & is preceded by a tilde(~).  They do not have a return type.  They do not take arguments.  Example: class Fun { ……. ~Fun() { ….. } }  C# manages memory dynamically & uses a garbage collector, to execute all destructors on exit.  This process is called finalization.
  • 154.  This refers to the object that called the method.  Used to distinguish between local & instance variables that have the same name.  Example: class Integers { int x; int y; public void SetXY(int x, int y) { this.x=x; this.y=y; } ….. ….. }
  • 155.  They are the variables whose value cannot be changed during program execution.  Example: public const int size=100;  Any attempt to change the value of a constant result in compilation error.  The const members are implicitly static.  Const members are accessed using class name.  Value must be set when cont is defined.
  • 156.  Allows us to decide the value of a constant member at run-time.  Also allows to have different constant values for different objects of the class.  The value of the member is set using constructor & cannot be modified later.  Can be declared as either static fields or instance fields.  Example: class Numbers { public readonly int m; public static readonly int n; public Numbers(int x) { m=x; } static Numbers() { n=100; } }
  • 157.  In C# private data members can only be accessed using methods of a class.  Such methods are called as an accessor methods.  Drawbacks of using these methods:  We have to code them manually.  User have to remember that they have to use accessor methods to work with data members.  C# provides ‘properties’ that has same capabilities as of accessor methods.  Using property we can access data members as if they are public.  Also referred to as smart fields.
  • 158. using System; class Number { private int number; public int Anumber { get { return number; } set { number=value; } } } class PropertyTest { public static void Main() { Number n=new Number(); n.Anumber=20; int m=n.Anumber; Console.WriteLine("Number="+m ); } }  Above class declares a get accessor method (getter) & a set accessor method (setter).
  • 159.  A property can omit either a get clause or a set clause.  A property that has only a getter is called a read-only property.  A property that has only a setter is called a write-only property.  Other features:  Properties can also represent dynamic data.  Properties are also inheritable.  Can be used with static keyword.
  • 160.  Indexers are locations indicators.  Used to access class objects.  An indexer looks like a property & is written like it but with 2 differences:  The indexer takes an index argument & looks like an array.  The indexer is declared using keyword this.  Also referred to as smart arrays.  Difference between indexers & properties:  A property can be static member, whereas an indexer is always an instance member.  A get accessor of a property corresponds to a method with no parameters, whereas for indexer it corresponds to same formal parameter list as the indexer.  A set accessor of a property corresponds to a method with a single parameter named value, whereas for indexer it corresponds to same formal parameter list as the indexer,plus the paramter named value.  It is an error for an indexer to declare a local variable with the same name as an indexer parameter.
  • 161. using System; using System.Collections; class MyClass { private string []data = new string[5]; public string this [int index] { get { return data[index]; } set { data[index] = value; } } } class MyClient { public static void Main() { MyClass mc = new MyClass(); mc[0] = “UniqueInfotech"; mc[1] = “18"; mc[2] = “Janardan Arcade"; mc[3] = “Dahanu"; mc[4] = “West"; Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc [1],mc[2],mc[3],mc[4]); } }
  • 163.  Inheritance is a process of constructing or designing one class from another.  Forms of Inheritance  Classical form  Containment form Feature X Feature Y Feature Z Feature X Feature Y Feature Z Feature P Base Class Derived Class
  • 164.  Represents a kind of relationship between two classes.  Example:  Here class A is referred to as base class, parent class or super class.  Class B is referred to as derived class, child class or sub class.  Also referred to as ‘is-a’ relationship.  Example:  Dog is-a type of animal  Ford is-a type of car Class A Class B
  • 165. A B A C B A D C B A B C Grandparent class Parent class Child class Single Inheritance Hierarchical Inheritance Multiple Inheritance Multilevel Inheritance
  • 166.  Also known as containership inheritance.  Example: class A { …. } class B { …. A a; //a is contained in b } B b; ….  Here object a is contained in object b.  This relationship is referred to as ‘has-a’ relationship.  The outer class B which contains the inner class A is termed the ‘parent’ class & the contained class A is termed a ‘child’ class.  Example:  Car has-a radio.  City has-a road.
  • 167.  Syntax: class subclass-name : baseclass-name { variable declaration; methods declaration; }
  • 168. using System; class Item { public void Company() { Console.WriteLine("Item Code=XYZ"); } } class Fan:Item { public void Model() { Console.WriteLine("Model=Classic"); } } class SimpleInheritance { public static void Main() { Fan f=new Fan(); f.Company(); f.Model(); } }
  • 169.  A derived class extends its direct base class. It can add new members to those it inherits. However, it cannot change or remove the definition of an inherited member.  A derived class can hide an inherited member.  A derived class can override an inherited member.  An instance of a class contains a copy of all instance fields declared in the class & its base class.  Constructors and destructors are not inherited.
  • 170.  Class Visibility :  A class may be declared as:  public: Accessible within & outside the program assembly  internal (default): Accessible only within program assembly  private: Accessible only within the class.  Class Members Visibility :  Can be declared as either:  public  private  protected  internal  protected internal Keyword Visibility Containing Classes Derived Classes Containing Program Anywhere Outside the program Private Y Protected Y Y Internal Y Y P.Internal Y Y Y Public y Y y Y
  • 171.  Constraints on the accessibility of members & classes when they are used in process of inheritance:  The direct base class of a derived class must be at least as accessible as the derived class itself.  Accessibility domain of a member is never larger than that of the class containing it.  The return type of a method must be as accessible as the method itself.
  • 172. using System; class Room { public int length; public int breadth; public Room(int x, int y) { length=x; breadth=y; } public int Area() { return(length*breadth); } } class BedRoom:Room { int height; public BedRoom(int x,int y,int z):base(x,y) { height=z; } public int Volume() { return(length*breadth*height); } } class InherTest { public static void Main() { BedRoom room1=new BedRoom(10,11,12); int area1=room1.Area(); int vol=room1.Volume(); Console.WriteLine("Area= "+area1); Console.WriteLine("Volume= "+vol); } }
  • 173.  Uses derived class as a super class  Here A servers as base class for B which in turn serves as base class for C.  The chain ABC is known as inheritance path.  This process may be extended to any number of levels.  Write a program to store & display student information using multilevel inheritance. A B C Grandparent class Parent class Child class
  • 174. Account Current Fixed-Deposit Savings Long Medium Short  Write a program to demonstrate use of hierarchical inheritance.
  • 175.  In derived class we can create a method with same signature as in base class.  This concept is called as method overriding.  This method can have same name, same arguments & same return type as a method in base class.  When the method is called, the method defined in the subclass is invoked & executed.  The method in base class should be specified as virtual.  The method in base class should be specified with keyword override.
  • 176. using System; class Super { public int x; public Super(int x) { this.x=x; } public virtual void Display() { Console.WriteLine("Super x="+x); } } class Sub:Super { int y; public Sub(int x,int y) : base(x) { this.y=y; } public override void Display() { Console.WriteLine("Super x="+x); Console.WriteLine("Sub y="+y); } } class Test { public static void Main() { Sub s1=new Sub(100,200); s1.Display(); } }
  • 177.  With the help of virtual & override keywords we can hide an method declared in a base class.  What if the class is provided by someone else?  Here the base class method cannot be declared as virtual.  To override such method use modifier new to tell the compiler the derived class method “hides” the base class method.  Example: using System; class Base { public void Display() { Console.WriteLine("Base Method"); } } class Derived:Base { public new void Display() { Console.WriteLine("Derived Method"); } } class HideTest { public static void Main() { Derived d=new Derived(); d.Display(); } }
  • 178.  At times we can have one base class & a number of different derived classes.  The top-most base class simply acts as a base for others & is not useful on its own.  We might not want to create an objects of such classes.  This can be done by making the class as abstract.  Example: abstract class Base { ……… } class Dervied:Base { …….. } ……. ……. Base b1; //Error Derived d1; //Ok  Characteristic:  It cannot be instantiated directly.  It can have abstract members.  We cannot apply a sealed modifier to it.
  • 179.  Method declaration includes the modifier abstract.  It is implicitly a virtual method & does not provide any implementation.  An abstract method does not have a method body.  Example: public abstract void Draw (int x, int y);  Characteristics: 1. It cannot have implementation. 2. Its implementation must be provided in non-abstract derived classes by overriding the method. 3. It can be declared only in abstract classes. 4. It cannot take either static or virtual modifiers. 5. An abstract definition is permitted to override a virtual method.
  • 180.  Prevent a class from being further sub classed.  Such classes are called sealed classes.  Example: sealed class AClass { ….. } sealed class BClass:Someclass { ….. }  Any attempt to inherit these classes will cause an error & compiler will not allow it.  Standalone utility classes are created as sealed classes.
  • 181.  When an instance method declaration includes the sealed modifier, the method is said to be a sealed method.  A derived class cannot override this method.  A sealed method is used to override an inherited virtual method with the same signature.  Example: class A { public virtual void Fun() { …… } } class B: A { public sealed override void Fun() { …… } }  Now any derived class of B cannot further override the method Fun().
  • 182.  Means ‘one name ….. many forms’.  Polymorphism can be achieved in two ways: Polymorphism Inclusion Polymorphism Operation Polymorphism Using Virtual Methods Using Overloaded Methods
  • 183.  Implemented using overloaded methods & operators.  Overloaded methods are selected for invoking by matching arguments, in terms of number, type & order.  This information is known to compiler at compile time.  Also called as early binding, or static binding or static linking.  Also known as compile time polymorphism.  Early binding means an object is bound to its method call at compile time.
  • 184. using System; class Dog { } class Cat { } class Operation { static void Call(Dog d) { Console.WriteLine("Dog is called"); } static void Call(Cat c) { Console.WriteLine("Cat is called"); } public static void Main() { Dog dog=new Dog(); Cat cat=new Cat(); Call(dog); Call(cat); } }
  • 185.  Achieved through use of virtual functions.  Assume class A implements virtual method M. Classes B & C are derived from A and override method M. When B is cast to A, a call to method M from A is dispatched to B. Similarly when C is cast to A, a call to method M from A is dispatched to C.  Also known as run-time polymorphism.  Since method is linked with a particular class much later after compilation, this process is also called late binding.  Also known as dynamic binding as the selection of method is done dynamically at run time.
  • 186. using System; class Maruti { public virtual void Display() { Console.WriteLine("Maruti Car"); } } class SX4:Maruti { public override void Display() { Console.WriteLine("SX4 Car") } } class Swift:Maruti { public override void Display() { Console.WriteLine("Swift Car"); } } class Inclusion { public static void Main() { Maruti m=new Maruti(); m=new SX4(); m.Display(); m=new Swift(); m.Display(); } }
  • 188.  C# does not support multiple inheritance.  A class cannot have more than one superclass.  C# provides an approach known as interface to support the concept of multiple inheritance.  An interface is a class with some differences:  All members of an interface are implicitly public & abstract.  An interface cannot contain constant fields, constructors & destructors.  Its members cannot be declared static
  • 189.  General Form: interface Interfacename { member declarations; }  Like classes, interfaces can also be extended.  That is, an interface can be sub interfaced from other interfaces.  General Form: interface name2:name1 { Members of name2 }  Note: An interface can not extend classes
  • 190. using System; interface Addition { int Add(); } interface Multiplication { int Mul(); } class Computation:Addition,Multiplication { int x,y; public Computation(int x,int y) { this.x=x; this.y=y; } public int Add() { return(x+y); } public int Mul() { return(x*y); } } class InterfaceTest { public static void Main() { Computation com=new Computation(10,20); Addition add=(Addition)com; //casting Console.WriteLine("Sum="+add.Add()); Multiplication mul=(Multiplication)com; Console.WriteLine("Product="+mul.Mul()); } }
  • 191. using System; interface Area { double Compute(double x); } class Square:Area { public double Compute(double x) { return(x*x); } } class Circle:Area { public double Compute(double x) { return(Math.PI*x*x); } } class Interface2 { public static void Main() { Square s=new Square(); Circle c=new Circle(); Area area; area=s as Area; Console.WriteLine("Area of Square="+area.Compute(10.2)); area=c as Area; Console.WriteLine("Area of Square="+area.Compute(10.2)); } }
  • 192.  A base class of a derived class may implement an interface.  When an object of the derived class is converted to the interface type, the inheritance hierarchy is searched for a class that directly implements the interface.  Example: using System; interface Display { void Print(); } class B:Display { public void Print() { Console.WriteLine("Base Display"); } } class D:B { public new void Print() { Console.WriteLine("Derived Display"); } } class Interface3 { public static void Main() { D d=new D(); d.Print(); Display dis=(Display)d; dis.Print(); } }
  • 193.  It may be possible that multiple interface have a method of a same name.  This may create a problem when a class implements more than one interface.  C# supports a technique known as explicit interface implementation, which allows a method to specify explicitly the name of the interface it is implementing.  Example: using System; interface I1 { void display(); } interface I2 { void display(); } class C1:I1,I2 { void I1.display() { Console.WriteLine("I1 Display"); } void I2.display() { Console.WriteLine("I2 Display"); } } class Interface4 { public static void Main() { C1 c=new C1(); I1 i1=(I1)c; i1.display(); I2 i2=(I2)c; i2.display(); } }
  • 194.  An abstract class can use an interface in the base class list.  Here the interface methods are implemented as abstract methods.  Example: interface A { void Method(); } abstract class B:A { ………. ………. public abstract void Method(); }  Here class B does not implement the interface method; it simply redeclares as a public abstract method.  It is the duty of the class that derives from B to override & implement the method.
  • 196.  The C# operators can be defined to work with the user-defined data types such as structs & classes.  C# has the ability to provide the operators with a special meaning for a data type.  This mechanism of giving such special meaning to an operator is known as operator overloading.  Following is list of operators that can be overloaded. Category Operators 1. Binary Arithmetic +,*,/,-,% 2. Unary Arithmetic +,-,++,-- 3. Binary bitwise &,|,^,<<,>> 4. Unary bitwise !,~,true,false 5. Relational Operators ==,!=,>=,<,<=,>
  • 197.  Following is list of operators that cannot be overloaded. Category Operators 1. Conditional operators &&,|| 2. Compound assignment +=,-=,*=,/=,%= 3. Other operators [ ],( ),=,?:,->,new,sizeof,typeof,is,as
  • 198.  Operator overloading gives us syntactical convenience.  It helps us to generate more readable code in a number of situations. These includes:  Financial programs.  Mathematical or physical modeling  Graphical programs  Text manipulations  General form of an operator method: public static retval operator op(arglist) { Method body….. }
  • 199. using System; class Space { int x,y,z; public Space(int a,int b, int c) { x=a; y=b; z=c; } public void Display() { Console.Write(" "+x); Console.Write(" "+y); Console.Write(" "+z); Console.WriteLine(); } public static Space operator -(Space s) { s.x=-s.x; s.y=-s.y; s.z=-s.z; return(s); } } class SpaceTest { public static void Main() { Space s=new Space(10,-20,30); Space q; Console.Write("S: "); s.Display(); q=-s; Console.Write("Q: "); q.Display(); } }
  • 200. using System; class Complex { double x,y; public Complex(){ } public Complex(double real,double imag) { x=real; y=imag; } public static Complex operator +(Complex c1,Complex c2) { Complex c3=new Complex(); c3.x=c1.x+c2.x; c3.y=c1.y+c2.y; return(c3); } public void display() { Console.Write(x); Console.Write(" + j"+y); Console.WriteLine(); } } class ComplexTest { public static void Main() { Complex a,b,c; a=new Complex(2.5,3.5); b=new Complex(1.6,2.7); c=a+b; c.display(); } }
  • 201.  C# supports six comparison operators that can be considered in three pairs:  == & !=  > & <=  < & >=  The significance of pairing is two-fold:  Within each pair, the second operator should always give exactly the opposite result to the first.  C# always requires us to overload the comparison operators in pairs. That is, if we overload ==, then we must overload != also, otherwise it is an error.
  • 202. using System; class Vector { int x,y,z; public Vector(int a,int b,int c) { x=a; y=b; z=c; } public static bool operator ==(Vector v1,Vector v2) { if(v1.x==v2.x && v1.y==v2.y) return(true); else return(false); } public static bool operator !=(Vector v1,Vector v2) { return(!(v1==v2)); } } class CompareTest { public static void Main() { Vector u1=new Vector(1,2,3); Vector u2=new Vector(1,2,3); if(u1==u2) Console.WriteLine("U1 is equal to U2"); else Console.WriteLine("U1 is not equal to U2"); } }
  • 204.  A delegate object is a special type of object that contains the details of a method rather than data.  Delegates in C# is used for two purposes:  Callback  Event Handling  Dictionary meaning of delegate is “a person acting for another person”, in C# it means a method acting for another method.  A delegate in C# is a class type object & is used to invoke a method that has been encapsulated into it at the time of its creation.
  • 205.  General Form:  modifier delegate return-type delegate-name(parameters);  Delegate is derived from System.Delegate class.  The modifier controls the accessibility of the delegate.  Delegate may take any of the following modifiers: new, public, private, protected, internal.  It is a class type & can be declared in any place where a class definition is permitted.  A delegate may be defined in the following places:  Inside a class  Outside all classes  As the top level object in a namespace.
  • 206.  The methods whose references are encapsulated into a delegate instances are known as delegate methods (or callable entities)  The signature & return type of delegate methods must exactly match the signature & return type of the delegate.
  • 207.  A delegate-creation-expression is used to create a new instance of a delegate.  General Form:  new delegate-type(expression)  Here the delegate-type is the name of the delegate declared earlier whose object is to be created.  Expression must be the method name.  The method & the object to which a delegate refers are determined when the delegate is instantiated.  This remains constant for the entire lifetime of the delegate.  It is not possible to change them, once the delegate is created.
  • 208.  When a delegate is invoked, it in turn invokes the method whose reference has been encapsulated into the delegate.  General Form:  delegate_object(parameter list);  The optional parameter list provides values for the parameters pf the method to be used.
  • 209. using System; //Delegate Declaration delegate int ArithOp(int x,int y); class MathOperation { public static int Add(int a,int b) { return(a+b); } public static int Sub(int a,int b) { return(a-b); } } class DelegateTest { public static void Main() { ArithOp op1=new ArithOp(MathOperation.Add); ArithOp op2=new ArithOp(MathOperation.Sub); int result1=op1(3,20); int result2=op2(40,20); Console.WriteLine("Result1="+re sult1); Console.WriteLine("Result2="+re sult2); } }
  • 210.  It is possible for delegates to hold & invoke multiple methods.  Such delegates are called multicast delegates.  Also known as combinable delegates.  They must satisfy following conditions:  Return type of such delegate must be void.  None of the parameters of the delegates can be declared as output parameters, using out keyword.  If D is a delegate & d1,d2,d3 & d4 are its instances, then the statements:  d3=d1+d2 //refers to two methods.  d4=d3-d2 //refers to only d1 method
  • 211. using System; delegate void MDelegate(); class DM { public static void Display() { Console.WriteLine("In Display"); } public static void Print() { Console.WriteLine("In Print"); } } class MDelegateTest { public static void Main() { MDelegate m1=new MDelegate(DM.Display); MDelegate m2=new MDelegate(DM.Print); MDelegate m3=m1+m2; MDelegate m4=m2+m1; MDelegate m5=m3-m2; m3(); m4();; m5(); } }
  • 212.  An event is a delegate type class member that is used by the object or class to provide a notification to other object that an event has occurred.  The client object can act on an event by adding an event handler to the event.  General Form:  modifier event type event-name;  Since events are based on delegates, we must first declare a delegate and then declare an instance of the delegate using the keyword event.
  • 213. using System; //Delegate Declaration delegate void EDelegate(string str); class EventClass { public event EDelegate Status; public void TriggerEvent() { Status("Event Triggered"); } } class EventTest { public static void Main() { EventClass ec=new EventClass(); EventTest et=new EventTest(); ec.Status+= new EDelegate(et.EventCatch); ec.TriggerEvent(); } public void EventCatch(string str) { Console.WriteLine(str); } }
  • 214. Managing Console I/O Operations
  • 215.  The methods for reading & writing to the console are provided by the System.Console class.  This class gives us access to the standard input, standard output & standard error streams: Stream Object Represents Console.In Standard Input Console.Out Standard Output Console.Error Standard Error
  • 216.  Supports two methods for obtaining input from the keyboard.  Read(): Returns a single character as int.  ReadLine(): Returns a string containing a line of text.
  • 217.  Supports two methods for writing to the console.  Write(): Outputs one or more values to the screen without a new line character.  WriteLine(): Outputs one or more values to the screen but adds a new line character at the end of the output.
  • 218.  Write a program in C# to print the following output: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9
  • 219.  Use overloaded WriteLine() method.  General Form:  Console.WriteLine(format-string, v1, v2, ….);  Format String contains both static text & markers which indicate  Where the values are to be printed.  How the values are to be formatted.  Example  Console.WriteLine(“Sum of {0} and {1} is {2}”,a,b,c);  We can also specify a width for the value using the format:  { n , w }  n is the index number  w is the width for the value  Example: int a=45; int b=976; int c=a+b; Console.WriteLine(“{0,5n+{1,5}n } ------- n{2,5}”,a,b,c); 4 5 + 9 7 6 ----------- 1 0 2 1