Programming in C#
Programming in C#
Chapter : 1
Introducing C#
What is C#?
Highlights of C#
Why C# ?????
The primary motivation while developing any language is the concern that it able to
handle the increasing complexity of programs that are robust, durable &
maintainable.
The history of major languages developed is as follows:
Ken Thompson
B
1970
Martin Richards
BPCL
1967
Dennis Ritchie
1972
1983
C++
Bjarne Stroustrup
1987
ANSI C
ANSI Committee
1991
Oak
James Gostling
1995
Java
Sun MicroSystems
1996
ANSI C++
2000
C#
ANSI Committe
Microsoft
Cont.
1.
2.
3.
4.
5.
6.
7.
8.
Evolution of C#
1.
2.
3.
4.
5.
.NET Platform
.NET Framework
C#
Cont
C++
Power
Concept
Concept
Component
Java
Orientation
Elegance
C#
VB
Productivity
Characteristics of C# (5 marks)
Simple
Consistent
C# simplifies C++ by eliminating irksome operators such as ->, ::, and pointers.
C# treats integers & Boolean data types as entirely different types.
C# supports an unified type system which eliminates the problem of varying ranges of
integer types.
All types are treated as objects.
Modern
Object-Oriented
Encapsulation
Inheritance
Polymorphism
Cont.
Type-Safe
Type safety promotes robust programs.
C# incorporates number of type-safe measures:
All dynamically allocated objects & arrays are initialized to zero
Use of any uninitialized variables produces an error message by the compiler
Access to arrays are range-checked
C# does not support unsafe casts
C# supports automatic garbage collection
Versionable
Making new versions of software modules work with the existing applications is
known as versioning
C# provides support for versioning with the help of new & override keywords.
Compatible
C# enforces the .NET common language specifications & therefore allows interoperation with other .NET languages
Interoperable
C# provides support for using COM objects, no matter what language was used to
author them.
Flexible
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
Changes Introduced
1.
2.
3.
4.
5.
6.
7.
8.
1.
2.
3.
4.
5.
6.
7.
8.
Macros
Multiple Inheritance
Templates
Pointers
Global Variables
Typedef statement
Default Arguments
Forward Declaration of Classes
Enhancements to C++
1.
2.
3.
4.
5.
6.
7.
Chapter : 2
Understanding .NET: The C# Environment
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.
Interprocess Communication
.NET Device
Software
.NET User
.NET Infrastructure
Experience
& Tools
.NET Experience
Services
.NET Framework
.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:
.NET Framework
ASP .NET
Windows Forms
(Web Services)
(User Interface)
Loading
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
forms
Web forms
Console applications
Web Services
Chapter : 3
Overview of C#
Introduction
A Simple C# Program
class SampleOne
{
public static void Main()
{
System.Console.WriteLine(C# is sharper than C++);
}
}
SampleOne.exe
NAMESPACES
System.Console.WriteLine();
Here System is a namespace in which the Console class is
located.
This class can be accessed using the dot operator.
C# supports using directive that can be used to import the
namespace System into the program.
using System;
class SampleTwo
{
public static void Main()
{
Console.WriteLine(Hello World!!!);
}
}
Adding Comments
comments (//)
Multiline comments (/* .. .. */)
using System;
class SampleThree
{
public static int Main()
{
Console.WriteLine(Hello World!!!);
return 0;
}
}
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]);
}
}
csc filename.cs/main:classname
Example :
multimain.cs/main:Class A
multimain.cs/main:Class B
OR
//multimain.cs
using System;
class A
{
public static void Main()
{
Console.Write(Class A);
}
}
class B
{
public static void Main()
{
Console.Write(Class B);
}
}
Syntax Errors
Logic Errors
using Systom;
class SampleTen
{
public static void main()
{
Console.Write(Hello);
}
}
1.
2.
3.
4.
Program Structure
Documentation Section
Optional
Optional
Interfaces Section
Optional
Classes Section
Optional
Essential
Chapter : 4
Literals, Variables & Data Types
Literals
Variables
Conditions:
Data Types
Types in C#
Value types
Reference types
Pointers
When a value of a variable is assigned to another variable,
the value is actually typed.
Predefined
Types
Pointers
User-defined
Types
Reference Types
Predefined
Types
User-defined
Types
Integers
Enumerations
Objects
Classes
Real Numbers
Structures
Strings
Arrays
Booleans
Delegates
Characters
Interfaces
Declarations of Variables
Syntax:
Default Values
Static variables
Instance variables
Array elements
Type
Default Value
char type
\x000
float type
0.0f
double type
0.0d
decimal type
0.0m
bool type
false
enum type
null
Constant Variables
const
int Rows=10
const int Cols=10
Advantages
Programs
Scope of Variables
Static variables
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
Chapter : 5
Operators & Expressions
Type of Operators
Arithmetic
operators
Relational operators
Logical operators
Assignment operators
Increment & decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators
Operator
Symbol
Action
Addition
Adds two
operands
x+y
Subtraction
xy
Multiplication
Multiplies two
operands
x*y
Division
Divides two
operand
x/y
Modulus
Gives the
remainder when
the operands are
divided.
Example
x%y
Exercise
Relational Operators.
Relational Operators.
Syntax: (ae-1 relational operator ae-2)
Operator
Symbol
Equal
==
Greater than
>
Less Than
<
>=
<=
Not Equal to
!=
Exercise
Logical operators
Operator
Symbol
AND
&&
OR
||
NOT
&
Bitwise logical Or
Syntax: v op=exp
Example:
is same as
x=x+(y+1);
Easier to read.
The statement is more concise
Results in more efficient code
Symbol
Action
Examples
Increment
++
Increments the
operand by one
++x, x++
Decrement
--
Decrements the
operand by one
--x, x--
Exercise:
Conditional Operator
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
*/%
+-
Type Conversion
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
Implicit Conversions
Explicit Conversions
Type Conversions
Implicit
Conversions
Explicit
Conversions
Arithmetic
Operations
Casting
Operations
Mathematical Functions
Method
Description
Sin()
Asin()
Sine of an angle in
radians
Cosine of an angle in
radians
Tanget of an angle in
radians
Inverse of Sine
Acos()
Inverse of Cosine
Atan()
Inverse of Tangent
Sinh()
Hyperbolic sine
Cos()
Tan()
Cosh()
Hyperbolic cosine
Tanh()
Hyperbolic tangent
Sqrt()
Square Root
Pow()
Exp()
Number raised to a
given power
Exponential
Log()
Natural logarithm
Abs()
Absolute value
Min()
Max()
Exercise:
Chapter : 6
Decision Making & Branching
The if Statement
boolean
expression
?
True
Statement
block
Statement-X
Next statement
False
Jumping
Exercise
Is an extension of if statement.
General form:
if (boolean-expression)
{
true-block statement (s);
}
else
{
false-block statement (s);
}
statement-x;
True
boolean
expression
?
False
False-Block
Statement
True-Block
Statement
Statement-X
Next statement
Exercise
False
Test
condition1
?
False
Statement-3
Statement-2
Statement-X
Next statement
True
Test
condition2
?
True
Statement-1
Exercise
Exercise
Example
using System;
class CityGuide
{
public static void main()
{
Example
switch(m)
{
case 1:
x=y;
goto case2;
case 2:
x=y+m;
goto default;
default:
x=y-m;
break;
}
Chapter : 7
Decision Making & Looping
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
}
Test False
cond
True
Body of the
loop
Example
class DowhileTest
{
public static void Main ( )
{
int two,count,y;
two = 2;
count=1;
System.Console.WriteLine("Multiplication Table \n");
while(count<=10)
{
y = two * count ;
System.Console.WriteLine("2 * " + count + " = " + y) ;
count = count + 1;
}
}
}
The Do Statement
Body of the
loop
Test
cond
False
True
Example
class DowhileTest
{
public static void Main ( )
{
int two,count,y;
two = 2;
count=1;
System.Console.WriteLine("Multiplication Table \n");
do
{
y = two * count ;
System.Console.WriteLine("2 * " + count + " = " + y) ;
count = count + 1;
}while ( count <= 10 ) ;
}
}
Exercise
Is an entry-controlled loop
Syntax:
for(initialization;testcondition;increment)
{
Body of the loop..
}
All the three actions, namely initialization,
testing & incrementing, are placed in the for
statement itself.
Exercise
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
do
{
{
.
if (condition)
break;
..
Exit..
from
} loop
Exit from
loop
..
if (condition)
break;
..
..
}while (.)
.
..
for (.)
{
if (error)
break;
..
..
Exit from
} loop
..
Exit from
loop
for (.)
{
for (..)
{
..
if (condition)
break;
do
if (..)
continue;
.
.
}
if (..)
continue;
.
..
} while (test condition);
if (.)
continue;
..
Labelled Jumps
Chapter : 8
Methods in C#
Declaring Methods
Example:
int Product(int x,int y)
{
int m=x*y;
return(m);
}
Description
new
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
private
The method can only be accessed inside the class to which it belongs.
static
virtual
abstract
A virtual method which defines the signature of the method, but doesnt
provide an implementation.
override
sealed
extern
Invoking Methods
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( );
// invoke the cube method
int y = M.Cube(5); //Method call
Console.WriteLine( y );
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 ) ;
}
}
Method Parameters
Parameters
Reference Parameters
Output Parameters
Parameter Arrays
Pass By Value
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);
}
}
Pass By Reference
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);
}
}
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);
}
}
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
}
}
Method Overloading
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);
}
Chapter : 9
Handling Arrays
Introduction
One-Dimensional Arrays
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:
Creation of Arrays:
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
Two-Dimensional Arrays
Example: v[4,5];
Example
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(" ");
}
}
}
Variable-Size Arrays
Initializing: x[1][1]=10;
System.Array Class
Method/Property
Purpose
Clear()
CopyTo()
GetLength()
array
Gives the number of elements in a given
GetValue()
Length
SetValue()
Reverse()
Sort()
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.
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:
Removing Elements:
Modifying Capacity:
city.Add(Delhi);
city.Add(Mumbai);
city.RemoveAt(1);
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]);
Purpose
Add()
Clear()
Contains()
CopyTo()
Insert()
Remove()
RemoveAt()
RemoveRange()
Sort()
Capacity
Count
Chapter : 10
Manipulating Strings
Introduction
String Methods
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
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
Cont.
Expression
Meaning
\bm
er\b
\bm\S*er\b
|,
Example
using System;
using System.Text; //for StringBuilder class
using System.Text.RegularExpressions;
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
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;
Example
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
}
}
Classes
Reference type & stored on
heap
Support Inheritance
Default Values
Field
Initialization
Constructors
Destructors
Permit initialization of
instance fields
Permit declaration of
parameterless constructors
Supported
Assignment
Structs
Value Type & stored on
stock
Do Not Support
Inheritance
Default value is the value
produced by zeroing out
the fields of struct
Do Not
Do Not
Not Supported
Copies the value
Enumerations
Example
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 );
}
}
Chapter : 12
Classes & Objects
Introduction
Polymorphism.
Accessibility Control
private
public
protected
internal
protected
internal
Objects
Example
using System;
class Rectangle
{
public int length, width;
class Rect
{
public static void Main()
{
int area1;
Rectangle rect1=new Rectangle();
rect1.GetData(12,10);
area1=rect1.RectArea();
Console.WriteLine("Area="+area1);
}
}
Constructors
using System;
class Rectangle
{
public int length, width;
class Rect
{
public static void Main()
{
int area1;
Rectangle rect1=new Rectangle(12,10);
area1=rect1.RectArea();
Console.WriteLine("Area="+area1);
}
Overloaded Constructors
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;
}
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);
Static Members
Restrictions on Static
Methods:
Example
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);
}
}
Static Constructors
Example:
class Abc
{
static Abc()
{
}
}
A class can have only one static constructor
Copy Constructors
Destructors
It is opposite to constructor.
Example:
class Fun
{
.
~Fun()
{
..
C# manages memory
dynamically & uses a
garbage collector, to execute
all destructors on exit.
This process is called
finalization.
Example:
class Numbers
{
public readonly int m;
public static readonly int n;
public Numbers(int x)
{
m=x;
}
static Numbers()
{
n=100;
}
}
Properties (IMP)
Example
using System;
class Number
{
private int number;
public int Anumber
{
get
{
return number;
}
set
{
class PropertyTest
{
public static void Main()
{
Number n=new Number();
n.Anumber=20;
int m=n.Anumber;
number=value;
Console.WriteLine("Number="+m);
}
Property (cont)
Indexers (IMP)
Example
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]);
}
}
Chapter : 13
Inheritance & Polymorphism
(IMP)
Introductoin
form
Containment form
Feature X
Feature Y
Feature Z
Base Class
Feature X
Feature Y
Feature Z
Feature P
Derived Class
Classical Inheritance
Example:
Class A
Class B
Example:
C
Hierarchical
Inheritance
Single Inheritance
Grandparent class
Parent class
Child class
Multilevel
Inheritance
C
Multiple
Inheritance
Containment Inheritance
Defining a Subclass
Syntax:
class subclass-name : baseclass-name
{
variable declaration;
methods declaration;
}
class SimpleInheritance
{
public static void Main()
{
Fan f=new Fan();
f.Company();
f.Model();
}
}
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.
Visibility Control
Class Visibility :
public
private
protected
internal
protected internal
Keyword
Visibility
Containing
Derived
Containing
Anywhere
Private
Classes
Y
Classes
Program
Protected
Internal
P.Internal
Public
Y
Y
Accessibility Constraints
Accessibility
The
}
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);
}
Multilevel Inheritance
Grandparent class
Parent class
Child class
Hierarchical Inheritance
Account
Savings
Fixed-Deposit
Current
Short
Medium
Long
Example
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;
class Test
{
public static void Main()
{
Sub s1=new Sub(100,200);
s1.Display();
}
}
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();
}
}
Abstract Classes
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.
Abstract Methods
1.
2.
3.
4.
5.
An abstract definition is
permitted to override a
virtual method.
Characteristics:
It cannot have
implementation.
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.
Sealed Methods
}
}
class B: A
{
public sealed override void Fun()
{
}
}
Now any derived class of B cannot further override the method Fun().
Polymorphism
Means one name .. many forms.
Polymorphism can be achieved in two ways:
Polymorphism
Operation
Polymorphism
Inclusion
Polymorphism
Using
Overloaded
Methods
Using
Virtual
Methods
Operation Polymorphism
Example
using System;
class Dog
{
}
class Cat
{
}
class Operation
{
static void Call(Dog d)
{
Console.WriteLine("Dog is
called");
}
Inclusion Polymorphism
Example
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();
}
}
Chapter : 14
Interfaces: Multiple Inheritance
Introduction
Defining an Interface
General Form:
interface Interfacename
{
member declarations;
}
General Form:
interface name2:name1
{
Members of name2
}
Note: An interface can not extend classes
Example: 1
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);
}
Multiplication mul=(Multiplication)com;
Console.WriteLine("Product="+mul.Mul());
}
class Interface2
{
public static void Main()
{
Square s=new Square();
Circle c=new Circle();
class Square:Area
{
public double Compute(double x)
{
return(x*x);
}
}
Area area;
area=s as Area;
class Circle:Area
{
public double Compute(double x)
{
return(Math.PI*x*x);
}
}
Console.WriteLine("Area of
Square="+area.Compute(10.2));
Console.WriteLine("Area of
Square="+area.Compute(10.2));
area=c as Area;
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();
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();
}
}
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
Operators
1. Binary Arithmetic
+,*,/,-,%
2. Unary Arithmetic
+,-,++,--
3. Binary bitwise
&,|,^,<<,>>
4. Unary bitwise
!,~,true,false
5. Relational Operators
==,!=,>=,<,<=,>
Cont
Operators
1. Conditional operators
&&,||
2. Compound assignment
+=,-=,*=,/=,%=
3. Other operators
[ ],( ),=,?:,->,new,sizeof,typeof,is,as
Financial programs.
Mathematical or physical modeling
Graphical programs
Text manipulations
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();
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();
}
}
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);
}
& !=
> & <=
< & >=
Example:
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);
}
Chapter : 16
Delegates & Events
(IMP)
Introduction
Callback
Event Handling
Delegate Declaration
General Form:
Inside a class
Outside all classes
As the top level object in a namespace.
Delegate Methods
Delegate Instantiation
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.
Delegate Invocation
delegate_object(parameter
list);
The optional parameter list provides values for the
parameters pf the method to be used.
Example:
using System;
//Delegate Declaration
delegate int ArithOp(int x,int y);
class DelegateTest
{
public static void Main()
{
class MathOperation
{
public static int Add(int a,int b)
{
return(a+b);
}
public static int Sub(int a,int b)
{
return(a-b);
}
}
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="+result1
);
Console.WriteLine("Result2="+result2
);
}
Multicast Delegate
Example
using System;
delegate void MDelegate();
class DM
{
public static void Display()
{
Console.WriteLine("In Display");
}
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();
Events(IMP)
Example
using System;
//Delegate Declaration
delegate void EDelegate(string str);
class EventClass
{
public event EDelegate Status;
class EventTest
{
public static void Main()
{
EventClass ec=new
EventClass();
EventTest et=new
EventTest();
ec.Status+= new
EDelegate(et.EventCatch);
ec.TriggerEvent();
}
Chapter : 17
Managing Console I/O Operations
Represents
Console.In
Standard Input
Console.Out
Standard Output
Console.Error
Standard Error
Console Input
ReadLine():
Console Output
WriteLine():
Exercise
Formatted Output
Example
Console.WriteLine(Sum of {0}
and {1} is {2},a,b,c);
{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,5\n+{1,5}\
n} ------- \n{2,5},a,b,c);
45
+976
----------1021
Numeric Formatting
Chapter : 18
Managing Errors & Exceptions
THANK YOU