Programming in C#
Programming in C#
Chapter : 1
Introducing C#
What is C#?
Is a compute-programming language developed by
Microsoft Corporation, USA.
2000 C# Microsoft
Cont….
C & C++ languages suffer from a VB, a language promoted by
number of shortcomings in Microsoft for overcoming these
meeting World Wide Web problems, is not truly object-
requirements & standards. oriented and becomes
Some are as follows: increasingly difficult to use when
systems become large.
1. The high complexity of language
Java which is truly object-
2. They are not truly object oriented has not retained some
oriented powerful C++ features such as
3. They have poor type safety operator overloading.
4. They are not suitable for Java also lacks inter-operability
working with new web with code developed in other
technologies. languages.
5. They do not support versioning Microsoft therefore decided to
6. Their low productivity design a new language.
7. They are weak in consistency
The result is C#, a simple &
modern language that directly
8. Their poor compatibility with addresses the needs of
the existing systems component-based software
development.
Evolution of C#
The Internet is the mainstream The outcome is a new generation
for many business organization platform called .NET.
today. Microsoft introduced C# as a de
There were a number of facto language of the .NET
limitations in using the WWW platform.
over the Internet: C# has been particularly designed
1. We could see only one site at a to build software components
time for .NET and it supports key
2. The site had to be authored to our features of .NET natively.
hardware environment C# compiler is embedded into
3. The information was basically .NET as shown below:
read-only.
4. We could not dynamically
compare similar information
stored on different sites. .NET Platform
5. The internet is a collection of
many information islands that do
not co-operate with each other. .NET Framework
Microsoft wanted to develop a
software platform which will
overcome these limitations &
make the Web both C#
programmable and intelligent.
Cont…
C# is a descendant of C++ which in turn is a
descendant of C as illustrated below:
C
Object
Orentation
C++
Concept Power Concept
Component
Java Orientation C# VB
Elegance Productivity
Characteristics of C# (5 marks)
Simple
C# simplifies C++ by eliminating irksome operators such as ->, ::, and pointers.
C# treats integers & Boolean data types as entirely different types.
Consistent
C# supports an unified type system which eliminates the problem of varying ranges of
integer types.
All types are treated as objects.
Modern
C# is called modern language bcoz it supports:
Automatic garbage collection
Rich intrinsic model for error handling
Decimal data types for financial applications
Modern approach to debugging
Robust security model
Object-Oriented
C# is truly object-oriented. It supports:
Encapsulation
Inheritance
Polymorphism
Cont….
Type-Safe
Type safety promotes robust programs.
C# incorporates number of type-safe measures:
All dynamically allocated objects & arrays are initialized to zero
Versionable
Making new versions of software modules work with the existing applications is
known as versioning
C# provides support for versioning with the help of new & override keywords.
Compatible
C# enforces the .NET common language specifications & therefore allows inter-
operation with other .NET languages
Interoperable
C# provides support for using COM objects, no matter what language was used to
author them.
Fexible
We may declare certain classes & methods as ‘unsafe’ and then use pointers to
manipulate them.
Applications of C#
C# is a new language developed exclusively to
suit the features of .NET platform.
It can be used for a variety of applications that
are supported by the .NET platform
Console applications
Windows applications
Developing Windows Controls
Developing ASP .NET Projects
Creating Web Controls
Providing Web Services
Developing .NET component library
How Does C# differs from C++ ?
Changes Introduced
1. C# compiles straight from source code to executable
code, with no object files
2. In C#, class definition does not use a semicolon at
end
3. The first character of Main() function is capitalized
4. C# does not support #include statement
5. C# does not support multiple code inheritance
6. Casting in C# is much more safer then C++
7. C# does not support default arguments
8. C# permits declaration of variables between goto &
label
How Does C# differs from C++ ?
C++ Features Dropped
1. Macros
2. Multiple Inheritance
3. Templates
4. Pointers
5. Global Variables
6. Typedef statement
7. Default Arguments
8. Forward Declaration of Classes
Enhancements to C++
1. Automatic Garbage Collection
2. Versioning Support
3. Strict Type-Safety
4. Properties to access data members
5. Delegates & Events
6. Boxing & Unboxing
7. Web Services
How Does C# differs from Java ?
1. C# has more primitive data types
2. Arrays are declared differently in C#
3. C# supports struct type & Java does not
4. Java does not provide for operator overloading
5. C# provides for better versioning support than Java
6. C# provides static constructors for initialization
7. Java does not directly support enumerations
8. C# uses is operator instead of instanceof operator in
Java
9. C# checks overflows uses checked statements
10. There is no labeled break statement in C#. The goto
statement is used to achieve this.
11. In Java, the switch statement can have only integer
expression, while C# supports either an integer or string
expressions
Chapter : 2
Understanding .NET: The C# Environment
The .NET STRATEGY
.NET is a software framework that includes
everything required for developing software for
web services.
COM Technology:
Overcomes the problems of maintaining and testing of software.
A program can be divided into number of independent components where each one offers a
particular service.
Each component can be developed & tested independently and then integrated into the main
system.
This technology is known as Component Object Model (COM) and the software built using COM is
referred to as componentware.
Benefits:
Reduces Complexity
Enhances software maintainability
Enables distributed development acrossmultiple organizations
The Origins of .NET Technology (cont…)
.NET Technology
Is third generation component model
Provides a new level of inter-operability compared to COM technology
Inter-module communication is achieved using Microsoft Intermedia
Language (MSIL) or simply IL
IL allows for true cross language integration
IL also provides metadata : describes characteristic of data including
datatypes & locations.
.NET also includes host of other languages & tools that enable us to
develop & implement Web-based applications easily.
.NET Framework
The .NET Framework (cont…)
The .NET framework is one of the tools provided by the .NET
infrastructure & tools component of the .NET platform.
The .NET framework provides an environment for building, deploying &
running web services & other applications.
It consists of three distinct technologies:
Common Language Runtime
Framework Base Classes
User & program interfaces(ASP .NET)
.NET Framework
Security
Garbage Collection
Class Loader
Memory Layout
Framework Base Classes
Allows to implement applications quickly
The functionality of the base framework classes resides in
the namespace called System
Provides:
Input/Output operations
String handling
Managing arrays, lists,maps,etc
Accessing files & file systems
Accessing the registry
Security
Windowing
Database management
Drawing
Managing errors & exceptions
Connecting to Internet
User & Program Interfaces
The .NET framework provides the following tools
for managing user & application interfaces:
Windows forms
Web forms
Console applications
Web Services
These tools enables users to develop user-friendly
desktop-based as well as web-based applications.
Benefits of the .NET Approach
The .NET technology provides a number of benefits to
developers & users.
using System;
class SampleTwo
{
public static void Main()
{
Console.WriteLine(“Hello World!!!”);
}
}
Adding Comments
Enhances readability & understanding of the
code.
Types of comments:
Single-linecomments (//)
Multiline comments (/* ….. ….. */)
Main Returning a Value
Main() can also return a value if it is declared as int instead of
void.
When the return type is int, we must include a return statement
at the end of the method.
using System;
class SampleThree
{
public static int Main()
{
Console.WriteLine(“Hello World!!!”);
return 0;
}
}
using System;
class SampleFive
{
public static void Main()
{
string name=“PentaSoft Technologies”;
Console.WriteLine(name);
}
}
Command Line Arguments
Can be used to take an input from a user.
Command line arguments are parameters supplied to the
Main method at the time of invoking it for execution
using System;
class SampleSix
{
public static void Main(string[] args)
{
string name=“Welcome to”;
Console.Write(name);
Console.Write(“ ”+args[0]);
Console.WriteLine(“ ”+args[1]);
}
}
MAIN with a Class
class Demo //class definition
{
public void display()
{
System.Console.WriteLine(“In Demo Class”);
}
}
class SampleSeven
{
public static void Main(string[] args)
{
Demo d=new Demo(); //creating d object
d.display(); //callinf display() function
}
}
Providing Interactive Input
using System;
class SampleEight
{
public static void Main(string[] args)
{
Console.Write(“Enter Your Name”);
string name=Console.ReadLine();
Console.WriteLine(“Hello ”+name);
}
}
Using Mathematical Functions
using System;
class SampleNine
{
public static void Main(string[] args)
{
double x=5.0;
double y;
y=Math.Sqrt(x);
Console.WriteLine(“y = ”+y);
}
}
Multiple Main Methods
In C# it is possible to have Main //multimain.cs
method in different classes. using System;
class A
In such situations there would be {
multiple entry points in the
program. public static void Main()
{
There should be only one. Console.Write(“Class A”);
}
This problem can be resolved by }
specifying which Main is to be
used to the compiler at the time
of compilation: class B
{
csc filename.cs/main:classname public static void Main()
Example : {
multimain.cs/main:Class Console.Write(“Class B”);
OR
multimain.cs/main:Class B }
}
Compile Time Errors
A program is never totally error-free Errors.cs(2.7): error cs0234: The type
Types of errors: or namespace name ‘Systom’ does not
exists in the class or namespace
Syntax Errors
Logic Errors
Syntax errors will be caught by the
The error message contains:
compiler
Logical errors should be eliminated by 1. Name of the file being
testing the program logic carefully. compiled(Errors.cs)
When the compiler cannot interpret 2. Line number & column position of the
what we are attempting to convey error(2.7)
through our code the result is syntax
error. 3. Error code as defined by the compiler
(cs0234)
4. Short description of error
Example:
using Systom;
class SampleTen
{
public static void main()
{
Console.Write(“Hello”);
}
}
Program Structure
The documentation section
consists of a set of comments Documentation Section Optional
giving the name of the
program, the author, date &
other details. Using Directive Section Optional
The using directive section
includes all those namespaces Interfaces Section Optional
that contain classes required
by the application
Classes Section Optional
A interface is similar to a
class but contains only
abstract classes.Used in Main Method Section Essential
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.
Chapter : 4
Literals, Variables & Data Types
Literals
Literals are the value constants assigned to
variables in a program.
Conditions:
Not begin with a digit
Uppercase & lowercase are distinct
It should not be a keyword
White space is not allowed
Name can be of any length
Data Types
Every variable in c# is associated with a data type
Types in C#
Value types
Reference types
Pointers
C# Data Types
•Booleans •Delegates
•Characters •Interfaces
Declarations of Variables
Variables are names of storage locations.
Syntax:
type variable1, variable2,……. variableN
Default Values
A variable is either explicitly assigned a value or automatically
assigned a default value.
Eg.
const int Rows=10
const int Cols=10
Advantages
Programs are easier to read & understand
Programs are easier to modify
Accidental errors are minimized
Scope of Variables
It is region of code within which the variable can be accessed.
Depends on type of the variable and its place of declaration.
Consider following Eg…
class ABC
{
static int m;
int n;
void fun(int x, ref int y, out int z, int[] a)
{
int j=10;
……..
……..
}
}
Static variables
Declared at the class level
Known as fields or field variables.
The scope of these variables begins at the place of their declaration & ends when the
Main method terminates.
The value parameter ‘x’ will exists till the end of fun() method
The reference & output parameters (y & z) do not create a new storage locations.
Their scope is same as the underlying variables that are passed as arguments.
Array element a[0] come into existence when an array instance is created, & cease
to exist when there are no references to that array instance.
Variables declared inside a method are called local variables.
Their scope is until the end of block inside which they are declared.
Boxing & Unboxing
In OOP, methods are invoked with the help of objects.
Value types such as int & long are not objects, we cannot
use them to call methods.
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.
Here the variable m & om exist but the value of om resides on the heap. The values
are independent of each other.
int m=100;
object om=m;
m=20;
Console.WriteLine(m); //m=20
Console.WriteLine(om); //om=10
Unboxing
It is the process of converting the object type back to the
value type.
int m=100;
object om=m; //box m
int n=(int)om; //unbox om back to an int
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment & decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators
Operator Symbol Action Example
Equal ==
Not Equal to !=
Exercise
Write a program to demonstrate use of relational
operators.
Logical operators
Operator Symbol
AND &&
OR ||
NOT !
Bitwise logical AND &
Bitwise logical Or |
Bitwise logical exclusive Or ^
The 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);
Eg.
a=10;
b=15;
x = (a > b) ? a :b;
Operator Precedence and Parentheses
Some rules are needed about the order in which operations are
performed.
*/% 1
+- 2
Type Conversion
Used to convert data of one type to another type.
Example:
byte b1=10;
byte b2=20;
byte b3=b1+b2;
Results in an error message because, when we add two
byte values, the compiler automatically converts them into
int types and the result is an integer.
Type Conversions
Hence code should be:
int b3=b1+b2; //no error
Implicit Explicit
Conversions Conversions
Ways of Type Conversion
Implicit Conversions
Arithmetic Casting
Explicit Conversions
Operations Operations
Mathematical Functions
Present in Math class of System Namespace.
Static Members: E and PI
Mathematical Methods in Math class:
Cosh() Hyperbolic cosine
Method Description
Tanh() Hyperbolic tangent
Sin() Sine of an angle in
radians
Sqrt() Square Root
Cos() Cosine of an angle in
radians Pow() Number raised to a
Tan() Tanget of an angle in given power
radians Exp() Exponential
Asin() Inverse of Sine
Log() Natural logarithm
Acos() Inverse of Cosine
Abs() Absolute value
Atan() Inverse of Tangent
Min() Lower of two numbers
Sinh() Hyperbolic sine
Max() Higher of two numbers
Exercise:-
General form:
if (boolean-expression)
{
statement-block;
}
statement-x;
Flowchart of simple if control
Entry
boolean False
expression
?
True
Jumping
Statement
block
Statement-X
Next statement
Exercise
Write a program that stores weight & height of
10 person in array & count number of person
with height greater than 170 & weight more than
55.
The IF….. ELSE Statement
Is an extension of if statement.
General form:
if (boolean-expression)
{
true-block statement (s);
}
else
{
false-block statement (s);
}
statement-x;
Flowchart of if…else control
Entry
True-Block False-Block
Statement Statement
Statement-X
Next statement
Exercise
Write a program that counts total of even & odd
numbers stored in an array ‘number’.
Nesting of If….Else Statements
Used when a series of decisions are involved.
General form:
if (test condition1)
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
Flowchart of nested if….else statements
Entry
Test True
False
condition1
?
Test
False True
condition2
?
Statement-3 Statement-2 Statement-1
Statement-X
Next statement
Exercise
Write a program that finds largest among 3
numbers using nested if..else statement.
The Else If Ladder
Used when multipath decisions are involved.
General form:
if (condition 1)
statement-1;
else if (condition 2)
statement-2;
else if (condition 3)
statement-3;
else if (condition n)
statement-n;
else
default-statement;
statement-x;
Exercise
Write a program that finds the grade of a student
using else if ladder.
The Switch Statement
If statements increases complexity of a Here, the expression must be an integer
program dramatically as the type or char or string type
alternatives increases.
The program becomes difficult to read
& follow. Value-1, value-2 … are constants or
C# offers an alternative with the help of constant expressions & are known as
switch statement case labels.
General Form:
switch(expression)
{
Block-1, block-2…… are statement lists
and may be zero or more statements.
case value-1:
block-1
break;
case value-2:
block-2
break;
--------------------
--------------------
--------------------
default:
default-block
break;
}
statement-x;
Example
using System;
class CityGuide
{
public static void main()
{
Console.WriteLine(“Select your choice”);
Console.WriteLine(“London”);
Console.WriteLine(“Bombay”);
Console.WriteLine(“Paris”);
Console.WriteLine(“Type your choice”);
String name = Console.ReadLine ( );
switch (name)
{
case “Bombay”:
Console.WriteLine(“Bombay : Guide 5”) ;
beak;
case “London”:
Console.WriteLine(“london : Guide 10”) ;
beak;
case “Paris”:
Console.WriteLine(“Paris : Guide 15”) ;
beak;
default:
Console.WriteLine(“Invalid choise”) ;
break;
}
}
}
Fallthrough in Switch Statement
In the absence of the break Example
statement in a case block, if the
control moves to the next block
without any problem, it is known switch(m)
as ‘fallthrough’. {
case 1:
Fallthrough is permitted in C, C+ x=y;
+ & Java.
goto case2;
case 2:
C# does not permit automatic
fallthrough, if the case block x=y+m;
contains some code. goto default;
default:
However, it is allowed if the case x=y-m;
block is empty. break;
}
If we want two consecutive case
blocks to be executed
continuously, we have to force the
process using the goto statement.
Chapter : 7
Decision Making & Looping
The While Statement
The process of repeatedly Entry based loop
executing a block of statements is
known as looping.
Is an entry-controlled loop
statement.
Is an exit-controlled loop
statement.
Body of the
The body of the loop is executed loop
at least once.
Syntax:
initialization; Test False
do cond
{
Body of the Loop…
True
}while(test condition);
Example
class DowhileTest
{
public static void Main ( )
{
int two,count,y;
two = 2;
count=1;
System.Console.WriteLine("Multiplication Table \n");
do
{
y = two * count ;
Syntax:
for(initialization;testcondition;increment)
{
Body of the loop…..
}
General form:
foreach(type variable in expression)
{
Body of the loop
}
in is a keyword.
Example
using System;
class ForeachTest
{
public static void Main()
{
int[] arryInt={11,22,33,44};
foreach(int m in arryInt)
{
Console.Write(" " + m);
}
Console.WriteLine();
}
}
Jumps in Loops
C# permits a jump from one statement to the end or
beginning of a loop as well as jump out of a loop.
Example
General form:
modifiers type methodname(formal-parameter-list)
{
method---body
}
Example:
int Product(int x,int y)
{
int m=x*y;
return(m);
}
List of Method Modifiers
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
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.
Invoking Methods
Once method is defined, they must be activated
for operations.
General form:
objectname.methodname(actual-parameter-list);
Example
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( );
Value Parameters
Reference Parameters
Output Parameters
Parameter Arrays
Pass By Value
By default, method using System;
parameters are passed by class PassByValue
value.
{
static void change (int m)
When a method is invoked,
the value of actual {
parameters are assigned to m = m+10;
the corresponding formal }
parameters.
public static void Main( )
{
Any changes to formal
parameters does not affect int x = 100;
the actual parameters. change (x);
Console.WriteLine("x =" +
There are 2 copies of x);
variables when passed by }
value. }
Pass By Reference
We can force the value parameters to using System;
be passed by reference. class PassByRef
{
Use ref keyword. static void Swap ( ref int x, ref int y )
{
This does not create a new storage int temp = x;
location.
x = y;
y = temp;
It represents the same storage
location as the actual parameter. }
public static void Main( )
When a formal parameter is declared {
as ref, the corresponding actual int m = 100;
argument in the method invocation
must be declared as ref. int n = 200;
Console.WriteLine("Before Swapping;");
Used when we want to change the Console.WriteLine("m = " + m);
values of variables in the calling Console.WriteLine("n = " + n);
method.
Swap (ref m , ref n );
Console.WriteLine("After Swapping;");
Console.WriteLine("m = " + m);
Console.WriteLine("n = " + n);
}
}
The Output Parameters
Used to pass results back to the calling method.
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);
}
}
Variable Argument Lists
We can define methods that can using System;
handle variable number of class Params
arguments using parameter
arrays. {
static void Parray (params int [ ]
arr)
Parameter arrays are declared
using the keyword params {
Console.Write("array elements
are:");
The parameter arrays should be a
one-dimensional arrays. 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
}
}
Method Overloading
Enables us to create more than one Console.WriteLine(add(312L,22L,21));
method with the same name, but with }
the different parameter lists &
different definitions. static int add(int a,int b)
{
Required when methods are required return(a+b);
to perform similar tasks but using }
different input parameters.
static float add(float a,float b)
{
Example
return(a+b);
}
using System;
static long add(long a,long b,int c)
class Overloading
{
{
return(a+b+c);
public static void Main()
}
{
}
Console.WriteLine(add(2,3));
Console.WriteLine(add(2.6F,3.1F));
Chapter : 9
Handling Arrays
Introduction
Array is a group of contiguous or related data
items that share a common name.
Example : marks[10]
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
Exercise
Write a program to sort an array of 5 number
taking from user as input.
Two-Dimensional Arrays
Allows to store table of values.
Example: v[4,5];
First index specifies the row & second index specifies the
column within that row.
Initializing: x[1][1]=10;
System.Array Class
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.
Example
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(" ");
}
}
ArrayList Class
Present in System.Collections namespace.
Can store a dynamically sized array of objects.
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;
Example
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]);
}
}
ArrayList Property & Methods
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.
Chapter : 10
Manipulating Strings
Introduction
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=@”\EGB\CSharp\String.cs”;tim
String Methods
String objects are immutable.
Methods:
Compare(), Concat(), Copy(), Equals(), Insert(),
Join(), Replace(), Split(), ToLower(), ToUpper(),
Trim(), TrimStart(), TrimEnd().
Example
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);
}
}
Mutable Strings
They cab be modified using StringBuilder class.
Example:
StringBuilder s=new StringBuilder(“abc”);
Methods:
Append(), Insert(), Remove(), Replace()
Property:
Capacity, Length, [ ]
Example
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);
}
}
Regular Expressions
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.
Cont….
Examples of Regular Expression:
Expression Meaning
“\bm” Any Word Beginning with m
“er\b” Any word Ending with er
“\bm\S*er\b” Any word beginning with m and ending with er
“|,” Any word separated by spaces or comma
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);
}
}
Chapter : 11
Structures & Enumerations
Structures
We can create our own value types using structures.
Struct data members are private by default & hence declare them as
public.
Example
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;
struct Number
{
int number;
public Number (int value)
{
number=value;
}
}
Data Type Reference type & stored on Value Type & stored on
heap stock
Inheritance Support Inheritance Do Not Support
Inheritance
Default Values Default value of a class Default value is the value
type is null produced by ‘zeroing out’
the fields of struct
Field Permit initialization of Do Not
Initialization instance fields
Constructors Permit declaration of Do Not
parameterless constructors
Destructors Supported Not Supported
General Form:
enum Shape
{
Circle,
Square,
Triangle
}
Here Circle has value 0, Square has value 1 & Triangle has
value 2.
Example
using System; class EnumTest
class Area {
public static void Main( )
{
{
public enum Shape {Circle,Square}
Area area = new Area ( );
public void AreaShape ( int x, Shape shape)
area.AreaShape ( 15, Area.Shape.Circle);
{ area.AreaShape ( 15, Area.Shape.Square);
double area; area.AreaShape ( 15, (Area.Shape) 1 );
switch (shape) area.AreaShape ( 15, (Area.Shape) 10 );
{ }
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;
}
}
}
Chapter : 12
Classes & Objects
Introduction
C# is a true object oriented language.
Creating an Object:
Rectangle rect; //declare
rect=new Rectangle(); //instantiate
Or
Rectangle rect=new Rectangle();
Console.WriteLine("Area="+area1);
public Rectangle(int x, int y)
}
{
}
length = x;
width = y;
}
public int RectArea( )
{
int area = length * width;
return (area);
}
}
Overloaded Constructors
• Constructors with same name as of class but class Area
different no. & name of arguments. {
• Also known as polymorphism. public static void Main()
{
using System;
int area1;
class Room
Room r1=new Room(12,10);
{
public int length, width; Room r2=new Room(12);
A static variable is
common to all instances of
a class.
Example:
class Abc
{
static Abc()
{
………
}
}
Example:
public Item(Item item)
{
code=item.code;
price=item.price;
}
…………
Item item2=new Item(item1);
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;
}
…..
…..
}
Constant Members (IMP)
They are the variables whose value cannot be changed
during program execution.
Example:
public const int size=100;
set
Above class declares a get accessor
method (getter) & a set accessor
{ method (setter).
number=value;
}
}
}
Property (cont…)
A property can omit either a get clause or a set clause.
Other features:
Properties can also represent dynamic data.
Properties are also inheritable.
Can be used with static keyword.
Indexers (IMP)
Indexers are locations indicators. Difference between indexers &
properties:
A property can be static
Used to access class objects. member, whereas an indexer is
always an instance member.
An indexer looks like a property
& is written like it but with 2 A get accessor of a property
differences: corresponds to a method with
The indexer takes an index no parameters, whereas for
argument & looks like an array. indexer it corresponds to same
formal parameter list as the
The indexer is declared using indexer.
keyword this.
A set accessor of a property
Also referred to as smart arrays. 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.
Forms of Inheritance
Classical
form
Containment form
Feature X
Feature X
Feature Y
Feature Y
Feature Z
Feature Z
Feature P
Base Class
Derived
Classical Inheritance
Represents a kind of relationship between two classes.
Example: Class A
Class B
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
Different Classical Inheritance Implementation
A A
B B C D
Hierarchical
Single Inheritance
Inheritance
A Grandparent class
A B
B Parent class
C Child class C
Multilevel Multiple
Inheritance Inheritance
Containment Inheritance
Also known as containership Here object a is contained in
inheritance. object b.
class Fan:Item
{
public void Model()
{
Console.WriteLine("Model=Classic");
}
}
Characteristic of Inheritance
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.
Keyword Visibility
Containing Derived Containing Anywhere
Classes Classes Program Outside the program
Private Y
Protected Y Y
Internal Y Y
P.Internal Y Y Y
Public y Y y Y
Accessibility Constraints
Constraints on the accessibility of members &
classes when they are used in process of
inheritance:
A Grandparent class
B Parent class
C Child class
Here A servers as base class for B which in turn serves as base
class for C.
Account
Characteristic:
It cannot be instantiated
directly.
It can have abstract members.
We cannot apply a sealed
modifier to it.
Abstract Methods
Method declaration includes Characteristics:
the modifier abstract. 1. It cannot have
implementation.
It is implicitly a virtual
method & does not provide 2. Its implementation must be
any implementation. provided in non-abstract
derived classes by overriding
An abstract method does not the method.
have a method body.
3. It can be declared only in
Example: abstract classes.
public abstract void Draw (int
x, int y); 4. It cannot take either static
or virtual modifiers.
5. An abstract definition is
permitted to override a
virtual method.
Sealed Classes: Preventing Inheritance
Prevent a class from being further sub classed.
Example:
sealed class AClass
{
…..
}
sealed class BClass:Someclass
{
…..
}
Any attempt to inherit these classes will cause an error & compiler will
not allow it.
Polymorphism
Operation Inclusion
Polymorphism Polymorphism
Using Using
Overloaded Virtual
Methods Methods
Operation Polymorphism
Implemented using overloaded methods & operators.
General Form:
interface name2:name1
{
Members of name2
}
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.
Chapter : 15
Operator Overloading
Introduction
The C# operators can be defined to work with the user-defined data
types such as structs & classes.
Category Operators
Category Operators
return(c3);
}
Overloading Comparison Operators
C# supports six comparison operators that can be
considered in three pairs:
== & !=
> & <=
< & >=
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.
General Form:
delegate_object(parameter list);
The optional parameter list provides values for the
parameters pf the method to be used.
Example:
using System; class DelegateTest
{
//Delegate Declaration public static void Main()
delegate int ArithOp(int x,int y); {
Console.WriteLine("Result2="+result2
);
}
}
Multicast Delegate
It is possible for delegates to hold & invoke multiple
methods.
General Form:
modifier event type event-name;
}
public void EventCatch(string
} str)
{
Console.WriteLine(str);
}
}
Chapter : 17
Managing Console I/O Operations
The Console Class
The methods for reading & writing to the console are
provided by the System.Console class.
1
22
333
4444
55555
666666
7777777
88888888
999999999
Formatted Output
Use overloaded WriteLine() Example:
method. int a=45;
General Form: int b=976;
Console.WriteLine(format-
string, v1, v2, ….); int c=a+b;