SlideShare uma empresa Scribd logo
1 de 62
Unit 4
Book 5- E.Balguruswamy,
Programming in C#, Tata Mc-Graw
Hill, 2nd Edition
1
Overview of C#
• Microsoft named their new language as C#, they wanted a better ,
smarter, sharper language than its ancestors C and C++.
• Developed only for .NET platform which provide tools and services that
fully exploit both computing and communication.
• Many features are incorporated from Java.
• Provides one-stop coding approach to maintenance.
• C# is used to develop two categories of programs
– Executable application programs
– Component libraries
• Executable programs are written to carry out certain tasks and require the
method Main in one the classes.
• Component libraries do not require a Main declaration, because they are
stand alone application.
2
C# programs
Executable
programs
Library
programs
CLR
output
application
programs
CLR
output
3
C# and .net
• C# is a new programming language introduced in.net
• With C# developers can quickly implement applications and
components using built-in capabilities of the .net framework.
• C# code is managed by CLR it becomes safer than C++
• Benefits of CLR
– Interoperability with other languages
– Enhanced security
– Versioning support
– Debugging support
– Automatic garbage collection
– XML support for web based application
4
Similarities and differences from JAVA
• C# complier produces an executable code.
• C# has more primitive data types
• C# data types are objects.
• Arrays are declared differently in C#
• Java uses static final to declare a class constant while C# uses
const
• java will have one public class in each file, while c# allows any
file arrangements.
• C# supports the struct type and Java does not.
• C# provides better versioning than java
5
• In java parameters are always passed by value, C# allows
parameters to be passed by reference by using ref keyword.
• In java, the switch statement can only have integer
expression, while C# supports either integer or string
expression.
• There is no labeled break statement in C#, goto is used to
achieve this.
• C# uses is operator instead of instanceof operator in Java
• C# allows a variable number of parameters using the params
keywords.
• C# provides fourth type of iteration called foreach.
6
A simple C# program
• Displays a line of text.
class sampleone
{
public staic void Main()
{
System.Console.WriteLine(“C# is sharper than C++”);
}
}
7
1. class declaration
– class is object-oriented construct
– class is the keyword and declares a new class.
– sampleone is a C# identifier, specifies the name of the class to be
defined.
2. Braces
– C# is block-structured language, enclosed by braces { and }
– Every class definition begins with ‘{‘ and ends with ‘}’
3. Main
– Must include this method in one of the classes.
– Starting point for executing the program.
– Can have any no. of classes but only one main method
8
• Has got keywords public, static , void
• public
– Is an access modifier, tells the C# complier that the main method is
accessible by any one.
• static
– Declares main method is global
– Can be called without creating an instance of the class.
• void
– States that main method does not return any value
9
4. Output line
– System.Console.WriteLine(“C# is sharper than C++”);
– Similar to java statement, printf() of C, cout<< of C++
– Writeline method is a static method of Console class, located in a
namespace System.
– Prints a line C# is sharper than C++
– Every statement in C# should end with a semi-colon
5. Executing the program
– After creating the source code, save with .cs file extension in your
folder in your system. Eg. Sampleone.cs
– For compiling the program, perform csc sampleone.cs
– Executable file(IL code), run by name, sample
10
Transformation of source code to output
C# code
IL code
Native machine
code
output
C# compilation
JIT compilation
Execution
(.cs file)
(.exe file)
11
Providing interactive input
• Using assignment statement
• Through command line arguments
using System;
class SampleEight
{
public static void Main()
{
Console.Write(“Enter your name”);
String name=Console.ReadLine();
Console.WriteLine(“Hello” +=name);
}
}
12
Output
Enter your name: John
Hello John
Using mathematical functions
class SampleNine
{
public static void Main()
{
double x=5.0;
double y;
y=Math.sqrt(x);
Console.WriteLine(“y = “+y);
}
}
13
Output
Y=2.23606
Compile time errors
• Real life applications consists of large number of statements
and have complex logic.
• They will have errors in them.
• Two types of errors
– Syntax errors
– Logic errors
• Syntax errors is caught by the complier and logic errors should
be eliminated by testing the program logic carefully.
• When compiler cannot interpret what we want to convey,
result is syntax error.
• Complier detects such an error and displays an appropriate
error message
14
//program with syntax errors
using systom; //error
class Sampleten
{
public static void main() //error
{
Console.WriteLine(“y = “+y) //error
}
}
15
• The complier could not locate a namespace called “systom”
and therefore produces an error message and then stops
compiling.
• Error message consists of
• Name of the file being complied (error.cs)
• Linenumber and column position of the error (2.7)
• Error code defined by the complier (CS0234)
• Short description about the error.
• Eg: error.cs(2.7):error cs0234: the type or namespace name
‘systom’ does not exist in class or namespace.
16
17
Program structure
Main method section
Documentation section
Using directive section
Interfaces section
Classes section
optional
optional
optional
optional
essential
Programming coding style
• C# is freeform language
• No indentation required , so that program works properly.
• But this is bad programming.
• Eg.
Console.WriteLine(“Enter your name”);
• Can be written as
Console.Write
(“Enter your name”);
• Or
Console.Write
(
“Enter your name”
);
18
Decision making
• If statement has different forms
– Simple if statement
– if..else statement
– nested if..else statement
– else if ladder
• Switch statement
• ?: operator
19
Simple if statement
if (boolean-expression)
{
Statement-block;
}
Statement x;
20
Boolean
expression
Statement block
false
true
entry
Statement x
Next Statement
The if..else statement
if (boolean-expression)
{
true-block Statement(s);
}
else
{
false-block statement(s);
}
Statement x;
21
Boolean
expression
True block Statement
true
entry
Statement x
Next Statement
False block Statement
false
Nested if..else statements
if(test condition1)
{
if(test condition2)
{
statement 1;
}
else
{
statement2;
}
}
else
{
statement 3;
}
statement x;
22
Test
condition1
Statement 3
false
entry
Statement x
Test
condition2
true
false
Statement 2
true
Statement 1
Else if ladder
if(condition1)
statement1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
…
else if
default-satement;
statement-x;
23
Switch operator
switch (expression)
{
case value-1: block-1;
break;
case-value-2:block-2;
break;
…
default: default-block;
break;
}
statement-x;
24
?: operator
• Conditional operator
• conditional expression ? expression1:expression2
• Conditional expression is evaluated first
• If result is true, expression 1 is evaluated
• If result is false, expression2 is evaluated
• Eg:
if(x<0)
flag=0;
else
flag=1;
• Can be written as
flag=(x<0)?0:1
25
Boxing and unboxing
• Methods are invoked using objects.
• Value types like int and long are not objects , we cannot use
them to call methods.
• Can be achieved using a technique called boxing.
• Boxing means the conversion of value type on the stack to a
object type on the heap.
• Unboxing means conversion of object type back into value
type
26
boxing
• When the complier 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.
int m=100;
Object om=m; //creates a box to hold m
• On execution, it creates a temporary reference_type ‘box’ to
old the object on heap.
• Boxing operation creates a copy of the value of m integer to
object om.
27
unboxing
• Unboxing is the process of converting the object type back to
value type.
• Unboxing is possible only for previously boxed variable.
int m=10;
object om=m; //box m
int n= (int) om;
• When unboxing , c# checks that the value type requested is
actually stored in the object under conversion. Only if it is,
the value is unboxed.
• We should ensure that, the value type is large enough to hold
the value of the object. Otherwise it may result in run-time
error.
28
Declaring methods
modifiers type methodname (formal-parameter-list)
{
method_body
}
• Five parts
– Name of the method
– Type of the value the method returns
– List of parameters
– Body of the method
– Method modifiers
29
int product(int x,int y)
{
int m=x*y;
return(m);
}
Invoking methods
• The process of activating a
method is known as
invoking or calling.
• Done using dot operator
• objectname.methodname(a
ctual-parameter-list);
• The values of the actual
parameters are assigned to
the formal parameters at
the time of invocation.
using System;
class method
{
int cube(int x)
{
return(x*x*x);
}
}
class methodtest
{
public static void Main()
{
method m=new method();
int y=m.cube(5);
Console.WriteLine(y);
}
}
30
Invoking a static method
using System;
class staticmethod
{
public static void Main()
{
double y=square(4);
Console.WriteLine(y);
}
static double square(int x)
{
return(x*x);
}
}
31
Pass by value
using System;
class method
{
static void func(int m)
{
m=m+10;
Console.Write(m);
}
}
class methodtest
{
public static void Main()
{
int x=100;
func(x);
Console.WriteLine(x);
}
}
32
Pass by reference
• ref keyword is used.
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,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);
}
}
33
Output parameters
• Using out keyword, to return values to the called functions.
using System;
class staticmethod
{
public static void Main()
{
int m,n;
square(4,out m,int n);
Console.WriteLine(m);
C.W(n);
}
static double square(int x, out int y, out int z)
{
y=x*x;
Z=x*x*x;
}
}
34
Variable parameter list
using System;
class params
{
static void parray(params int [] arr)
{
C.W(“array elemets are:”);
foreach(int i in arr)
C.W(“ “ +i);
}
public static void main()
{
int x={11,22,33};
parray(x);
parray();
parray(100,200);
}
}
35
Methods overloading
using System;
class overloading
{
public static void main()
{
C.W(volume(10));
C.W(volume(2.5 F,8));
C.W(volume(100L,75,15));
}
static int volume(int x)
{
return (x*x*x); //cube
}
static double volume(float r,int h)
{
return(3.14*r*r*h); //cylinder
}
static long volume( long l,int b,int h)
{
return(l*b*h); //box
}
36
Defining a class
class classname
{
[variables declaration;]
[methods declaration;]
}
• Class is user defined data type with a template that serves to
define its properties
• Class is the keyword, classname is the valid C# identifier
• Everything inside [ ] is optional.
37
Adding variables
• Data is encapsulated in a class by placing data fields inside
the body of the class definition.
• These variables are called instance variables because they are
created whenever a object of the class of instantiated.
class rectangle
{
int length;
int width;
}
38
Adding methods
• A class with only data fields and no methods that operate on that
data has no life.
type methodname (parameter-list)
{
method-body;
}
class rectangle
{
int length;
int width;
public void getdata(int x,int y)
{
length=x;
length=y;
}
}
39
Member access modifiers
• Private,Public,Protected,Internal,Protected internal
• By default it is private
class visiblity
{
public int x;
internal int y;
protected double d;
float p; //private by default
}
40
Creating objects
• Objects are created in C# using the new operator.
• The new operator creates an object of the specified class and
returns a reference to that object.
• rectangle rect1; //declare
• rec1=new rectangle(); //instantiate
• rectangle()is default constructor of the class.
41
Accessing class members
• objectname.variablename;
• objectname.methodname(parameter_list);
• rect1.length=15;
• rect1.width=10;
• Constructors:
• It enables an object to initialize itself when it is created.
• Same name as that of the class.
• Do not have any return type, not even void.
42
Overloaded constructors
• Methods have same name,
different parameter list and
different definitions method
overloading.
• Used to perform simple tasks
which requires different types of
parameter list.
• Also known as polymorphism.
• Each parameter list should be
unique.
• rect r1=new rect(10,20);
• rect r2=new rect(10);
class rectangle
{
public int length;
public int width;
public rectangle(int x,int y)
{
length=x; width=y;
}
public rectangle(int x)
{
length=width=x;
}
public int area()
{
return(length*width);
}
}
43
Static constructors
• Called before any objects of the class is created.
• Used to assign initial values to static data
members.
class abc{
static abc(){
..
}
..
}
44
• Private constructors
– All declarations must be contained in the class
– Creating objects using such classes may be prevented by adding a
private constructor to the class.
• Copy constructors
– Creates an object by copying variables from another object.
• C# does not provide a copy constructor. We have to define.
public item(item item)
{
code=item.code;
price=item.price;
}
• Copy constructor is invoked by instantiating an object of type
Item and passing it object to be copied.
• Item item2=new item(item1);
45
deconstructors
• Opposite of constructors.
• Name is same as that of the constructor , preceded by ~.
class fun
{…
~fun(){..}
}
• C# manages the memory dynamically and uses a garbage
collector, executes all deconstructors on exit.
• The process of calling a deconstructors when an object is
reclaimed by the garbage collector is called finalization.
46
This reference
class integers
{
int x;
int y;
public void setxy(int x,inty)
{
this.x=x;
this.y=y;
}
…
}
47
Nesting of classes
public class outer
{
…. // members of outer class
public class inner
{
….//members of inner class
}
}
48
Constant members
• Allows declaration of data fields of a class as constant.
• public const int size=100;
• Member size is initialized 100 during compilation , it cannot
be changed later.
• Any attempt done to assign a value to it, will result in
compilation error.
• Const members are implicitly static.
• public static const int size=100;
• Will produce compile time error, we cannot declare explicitly
using static
49
read-only members
• Using readonly modifier, we can set the value of the member
using a constructor method, cannot be modified later.
• Declared as static fields or instance fields.
class numbers
{
public readonly int m;
public static readonly int n;
public numbers(int x)
{ m=x; }
static numbers()
{ n=100; }
}
50
properties
• Accessor methods to
access the data members
• Mutator method  to set
the value of the data
members
• Drawback:
• We have to code accessor
methods manually
• Uses should remember that
they have to use accessor
methods to work with data
members
using system;
class number
{
private int number;
public int anumber; //property
{
get
return number;
set
number=value;
}
}
class propertytest
{
public void static main()
{
number n=new number();
n.anumber=100;
int m=n.anumber;
Console.WriteLine(“Number=”+m);
}
} 51
indexers
• They are location indicators
• Used to access class objects just like accessing elements in array
• Useful when class is container of other classes.
• The indexer takes an index argument and looks like an array
• The indexer is declared using name this.
• Implemented using get and set accessors for the [] operator.
public double this[int idx]
{
get
{ //return desired data }
set
{//set desired data }
}
52
Defining an interface
• it contains one or more methods, properties, indexers, events
but none of them are implemented in the interface itself.
interface interface_name
{
member declarations;
}
eg. interface show
{
void display();
}
53
Extending an interface
Interface l1
{
….
}
interface l2
{
….
}
interface l3:l2,l1
{
….
}
54
Interface name2:name1
{
members of name2
}
• Eg:
interface addition
{
int add(intx,int y);
}
interface compute:addition
{
int sub(int x, int y);
}
Implementing interfaces
class classname :interfacename
{
body of classname
}
• Here classname implements the interfacename
class a:b,l1,l2
{
…
}
• Where B is the base class and l1,l2 are the interfaces
55
Abstract class and interfaces
interface a
{
void method();
}
abstract class b:a
{
..
public abstract void method();
}
56
Delegates
• Dictionary meaning of “Delegate” means a person acting for
another person.
• In C# it means a method acting for another method.
• It is used to invoke a method that has been encapsulated into
it at time of its creation.
• Has four steps
– Delegate declaration
– Delegate methods definition
– Delegate instantiation
– Delegate invocation
57
Delegate declaration
• A delegate declaration defines a class using that
System.Delagate base class.
• Delegate methods are any functions whose signature matches
the delegate signature exactly.
• modifier delegate return-type delegate-name(parameters);
• Delegate may be defined in the following places
– Inside a class
– Outside a class
– As top level object in a namespace.
• Delegates are implicitly sealed.
58
Delegate methods
• Methods whose references are encapsulated into a delegate
instance are known as delegate methods or callable entities.
• The signature and return type of the delegate methods must
exactly match the signature and return type of the delegate.
• They do not care
– What type of object the method is being called against.
– Whether the method is static or instance method.
59
Delegate instantiation
• New delegate-type(expression)
• Delegate-type is the name of the delegate declared earlier whose
object is to be created.
• Expression must be method name or value of delegate type.
delegate int productdelegate(int x,int y);
class delegate
{
static int product (int a,int b)
return (a*b);
//delegate instantiation
productdelegate p=new productdelegate(product);
}
60
Delegate invocation
• delegate_object(parameter_list)
• If the invocation return void, the result is nothing and
therefore it cannot be used as an operand of any operator.
• Eg. delegate(x,y);
• If a method returns a value, then it can be used as an operand
of any operator.
• Eg. double result= delegate(2.56,45.73);
61
Events
• An event is a delegate type class member that is used by the
object or class to provide a notification to other objects that
an event has occurred.
• The client object can act on an event by adding an event
handler to the event.
• modifier event type event-name;
• Modifiers can be static,virtual,override,abstarct,sealed.
• Typedelegate.
• Eg: public event EventHandler click;
• EventHandler is a delegate and click is an event.
62

Mais conteúdo relacionado

Mais procurados

01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
Tareq Hasan
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
FALLEE31188
 

Mais procurados (20)

Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C programming interview questions
C programming interview questionsC programming interview questions
C programming interview questions
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
2. data, operators, io
2. data, operators, io2. data, operators, io
2. data, operators, io
 
C# in depth
C# in depthC# in depth
C# in depth
 
C++ programming language basic to advance level
C++ programming language basic to advance levelC++ programming language basic to advance level
C++ programming language basic to advance level
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 
Deep C
Deep CDeep C
Deep C
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
Oops
OopsOops
Oops
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C# note
C# noteC# note
C# note
 
Oop l2
Oop l2Oop l2
Oop l2
 
The smartpath information systems c plus plus
The smartpath information systems  c plus plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming Language
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 

Destaque

Destaque (20)

Control statements
Control statementsControl statements
Control statements
 
Chap2 comp architecture
Chap2 comp architectureChap2 comp architecture
Chap2 comp architecture
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Chap2 class,objects
Chap2 class,objectsChap2 class,objects
Chap2 class,objects
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
Chap1 packages
Chap1 packagesChap1 packages
Chap1 packages
 
output devices
output devicesoutput devices
output devices
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
FIT-Unit3 chapter 1 -computer program
FIT-Unit3 chapter 1 -computer programFIT-Unit3 chapter 1 -computer program
FIT-Unit3 chapter 1 -computer program
 
Using Input Output
Using Input OutputUsing Input Output
Using Input Output
 
Module1 part2
Module1 part2Module1 part2
Module1 part2
 
java-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of appletjava-Unit4 chap2- awt controls and layout managers of applet
java-Unit4 chap2- awt controls and layout managers of applet
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
 
Module1 Mobile Computing Architecture
Module1 Mobile Computing ArchitectureModule1 Mobile Computing Architecture
Module1 Mobile Computing Architecture
 
Chap3 primary memory
Chap3 primary memoryChap3 primary memory
Chap3 primary memory
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Chap2 input devices
Chap2 input devicesChap2 input devices
Chap2 input devices
 
Chap1 computer basics
Chap1 computer basicsChap1 computer basics
Chap1 computer basics
 

Semelhante a C#unit4

Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
Connex
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
Muhammad Abdullah
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
Connex
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
tarifarmarie
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
Rajb54
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
Alpana Gupta
 

Semelhante a C#unit4 (20)

java vs C#
java vs C#java vs C#
java vs C#
 
Basics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptxBasics of C Lecture 2[16097].pptx
Basics of C Lecture 2[16097].pptx
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
 
C# p3
C# p3C# p3
C# p3
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
 
Introduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdfIntroduction-to-C-Part-1.pdf
Introduction-to-C-Part-1.pdf
 
C# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net FrameworkC# lecture 1: Introduction to Dot Net Framework
C# lecture 1: Introduction to Dot Net Framework
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 
Cordovilla
CordovillaCordovilla
Cordovilla
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 

Mais de raksharao

Mais de raksharao (17)

Unit 1-logic
Unit 1-logicUnit 1-logic
Unit 1-logic
 
Unit 1 rules of inference
Unit 1  rules of inferenceUnit 1  rules of inference
Unit 1 rules of inference
 
Unit 1 quantifiers
Unit 1  quantifiersUnit 1  quantifiers
Unit 1 quantifiers
 
Unit 1 introduction to proofs
Unit 1  introduction to proofsUnit 1  introduction to proofs
Unit 1 introduction to proofs
 
Unit 7 verification &amp; validation
Unit 7 verification &amp; validationUnit 7 verification &amp; validation
Unit 7 verification &amp; validation
 
Unit 6 input modeling problems
Unit 6 input modeling problemsUnit 6 input modeling problems
Unit 6 input modeling problems
 
Unit 6 input modeling
Unit 6 input modeling Unit 6 input modeling
Unit 6 input modeling
 
Unit 5 general principles, simulation software
Unit 5 general principles, simulation softwareUnit 5 general principles, simulation software
Unit 5 general principles, simulation software
 
Unit 5 general principles, simulation software problems
Unit 5  general principles, simulation software problemsUnit 5  general principles, simulation software problems
Unit 5 general principles, simulation software problems
 
Unit 4 queuing models
Unit 4 queuing modelsUnit 4 queuing models
Unit 4 queuing models
 
Unit 4 queuing models problems
Unit 4 queuing models problemsUnit 4 queuing models problems
Unit 4 queuing models problems
 
Unit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generationUnit 3 random number generation, random-variate generation
Unit 3 random number generation, random-variate generation
 
Unit 1 introduction contd
Unit 1 introduction contdUnit 1 introduction contd
Unit 1 introduction contd
 
Unit 1 introduction
Unit 1 introductionUnit 1 introduction
Unit 1 introduction
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
FIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer LanguagesFIT-Unit3 chapter2- Computer Languages
FIT-Unit3 chapter2- Computer Languages
 
Chap1 secondary storage
Chap1 secondary storageChap1 secondary storage
Chap1 secondary storage
 

Último

Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 

C#unit4

  • 1. Unit 4 Book 5- E.Balguruswamy, Programming in C#, Tata Mc-Graw Hill, 2nd Edition 1
  • 2. Overview of C# • Microsoft named their new language as C#, they wanted a better , smarter, sharper language than its ancestors C and C++. • Developed only for .NET platform which provide tools and services that fully exploit both computing and communication. • Many features are incorporated from Java. • Provides one-stop coding approach to maintenance. • C# is used to develop two categories of programs – Executable application programs – Component libraries • Executable programs are written to carry out certain tasks and require the method Main in one the classes. • Component libraries do not require a Main declaration, because they are stand alone application. 2
  • 4. C# and .net • C# is a new programming language introduced in.net • With C# developers can quickly implement applications and components using built-in capabilities of the .net framework. • C# code is managed by CLR it becomes safer than C++ • Benefits of CLR – Interoperability with other languages – Enhanced security – Versioning support – Debugging support – Automatic garbage collection – XML support for web based application 4
  • 5. Similarities and differences from JAVA • C# complier produces an executable code. • C# has more primitive data types • C# data types are objects. • Arrays are declared differently in C# • Java uses static final to declare a class constant while C# uses const • java will have one public class in each file, while c# allows any file arrangements. • C# supports the struct type and Java does not. • C# provides better versioning than java 5
  • 6. • In java parameters are always passed by value, C# allows parameters to be passed by reference by using ref keyword. • In java, the switch statement can only have integer expression, while C# supports either integer or string expression. • There is no labeled break statement in C#, goto is used to achieve this. • C# uses is operator instead of instanceof operator in Java • C# allows a variable number of parameters using the params keywords. • C# provides fourth type of iteration called foreach. 6
  • 7. A simple C# program • Displays a line of text. class sampleone { public staic void Main() { System.Console.WriteLine(“C# is sharper than C++”); } } 7
  • 8. 1. class declaration – class is object-oriented construct – class is the keyword and declares a new class. – sampleone is a C# identifier, specifies the name of the class to be defined. 2. Braces – C# is block-structured language, enclosed by braces { and } – Every class definition begins with ‘{‘ and ends with ‘}’ 3. Main – Must include this method in one of the classes. – Starting point for executing the program. – Can have any no. of classes but only one main method 8
  • 9. • Has got keywords public, static , void • public – Is an access modifier, tells the C# complier that the main method is accessible by any one. • static – Declares main method is global – Can be called without creating an instance of the class. • void – States that main method does not return any value 9
  • 10. 4. Output line – System.Console.WriteLine(“C# is sharper than C++”); – Similar to java statement, printf() of C, cout<< of C++ – Writeline method is a static method of Console class, located in a namespace System. – Prints a line C# is sharper than C++ – Every statement in C# should end with a semi-colon 5. Executing the program – After creating the source code, save with .cs file extension in your folder in your system. Eg. Sampleone.cs – For compiling the program, perform csc sampleone.cs – Executable file(IL code), run by name, sample 10
  • 11. Transformation of source code to output C# code IL code Native machine code output C# compilation JIT compilation Execution (.cs file) (.exe file) 11
  • 12. Providing interactive input • Using assignment statement • Through command line arguments using System; class SampleEight { public static void Main() { Console.Write(“Enter your name”); String name=Console.ReadLine(); Console.WriteLine(“Hello” +=name); } } 12 Output Enter your name: John Hello John
  • 13. Using mathematical functions class SampleNine { public static void Main() { double x=5.0; double y; y=Math.sqrt(x); Console.WriteLine(“y = “+y); } } 13 Output Y=2.23606
  • 14. Compile time errors • Real life applications consists of large number of statements and have complex logic. • They will have errors in them. • Two types of errors – Syntax errors – Logic errors • Syntax errors is caught by the complier and logic errors should be eliminated by testing the program logic carefully. • When compiler cannot interpret what we want to convey, result is syntax error. • Complier detects such an error and displays an appropriate error message 14
  • 15. //program with syntax errors using systom; //error class Sampleten { public static void main() //error { Console.WriteLine(“y = “+y) //error } } 15
  • 16. • The complier could not locate a namespace called “systom” and therefore produces an error message and then stops compiling. • Error message consists of • Name of the file being complied (error.cs) • Linenumber and column position of the error (2.7) • Error code defined by the complier (CS0234) • Short description about the error. • Eg: error.cs(2.7):error cs0234: the type or namespace name ‘systom’ does not exist in class or namespace. 16
  • 17. 17 Program structure Main method section Documentation section Using directive section Interfaces section Classes section optional optional optional optional essential
  • 18. Programming coding style • C# is freeform language • No indentation required , so that program works properly. • But this is bad programming. • Eg. Console.WriteLine(“Enter your name”); • Can be written as Console.Write (“Enter your name”); • Or Console.Write ( “Enter your name” ); 18
  • 19. Decision making • If statement has different forms – Simple if statement – if..else statement – nested if..else statement – else if ladder • Switch statement • ?: operator 19
  • 20. Simple if statement if (boolean-expression) { Statement-block; } Statement x; 20 Boolean expression Statement block false true entry Statement x Next Statement
  • 21. The if..else statement if (boolean-expression) { true-block Statement(s); } else { false-block statement(s); } Statement x; 21 Boolean expression True block Statement true entry Statement x Next Statement False block Statement false
  • 22. Nested if..else statements if(test condition1) { if(test condition2) { statement 1; } else { statement2; } } else { statement 3; } statement x; 22 Test condition1 Statement 3 false entry Statement x Test condition2 true false Statement 2 true Statement 1
  • 23. Else if ladder if(condition1) statement1; else if(condition 2) statement 2; else if(condition 3) statement 3; … else if default-satement; statement-x; 23
  • 24. Switch operator switch (expression) { case value-1: block-1; break; case-value-2:block-2; break; … default: default-block; break; } statement-x; 24
  • 25. ?: operator • Conditional operator • conditional expression ? expression1:expression2 • Conditional expression is evaluated first • If result is true, expression 1 is evaluated • If result is false, expression2 is evaluated • Eg: if(x<0) flag=0; else flag=1; • Can be written as flag=(x<0)?0:1 25
  • 26. Boxing and unboxing • Methods are invoked using objects. • Value types like int and long are not objects , we cannot use them to call methods. • Can be achieved using a technique called boxing. • Boxing means the conversion of value type on the stack to a object type on the heap. • Unboxing means conversion of object type back into value type 26
  • 27. boxing • When the complier 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. int m=100; Object om=m; //creates a box to hold m • On execution, it creates a temporary reference_type ‘box’ to old the object on heap. • Boxing operation creates a copy of the value of m integer to object om. 27
  • 28. unboxing • Unboxing is the process of converting the object type back to value type. • Unboxing is possible only for previously boxed variable. int m=10; object om=m; //box m int n= (int) om; • When unboxing , c# checks that the value type requested is actually stored in the object under conversion. Only if it is, the value is unboxed. • We should ensure that, the value type is large enough to hold the value of the object. Otherwise it may result in run-time error. 28
  • 29. Declaring methods modifiers type methodname (formal-parameter-list) { method_body } • Five parts – Name of the method – Type of the value the method returns – List of parameters – Body of the method – Method modifiers 29 int product(int x,int y) { int m=x*y; return(m); }
  • 30. Invoking methods • The process of activating a method is known as invoking or calling. • Done using dot operator • objectname.methodname(a ctual-parameter-list); • The values of the actual parameters are assigned to the formal parameters at the time of invocation. using System; class method { int cube(int x) { return(x*x*x); } } class methodtest { public static void Main() { method m=new method(); int y=m.cube(5); Console.WriteLine(y); } } 30
  • 31. Invoking a static method using System; class staticmethod { public static void Main() { double y=square(4); Console.WriteLine(y); } static double square(int x) { return(x*x); } } 31
  • 32. Pass by value using System; class method { static void func(int m) { m=m+10; Console.Write(m); } } class methodtest { public static void Main() { int x=100; func(x); Console.WriteLine(x); } } 32
  • 33. Pass by reference • ref keyword is used. 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,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); } } 33
  • 34. Output parameters • Using out keyword, to return values to the called functions. using System; class staticmethod { public static void Main() { int m,n; square(4,out m,int n); Console.WriteLine(m); C.W(n); } static double square(int x, out int y, out int z) { y=x*x; Z=x*x*x; } } 34
  • 35. Variable parameter list using System; class params { static void parray(params int [] arr) { C.W(“array elemets are:”); foreach(int i in arr) C.W(“ “ +i); } public static void main() { int x={11,22,33}; parray(x); parray(); parray(100,200); } } 35
  • 36. Methods overloading using System; class overloading { public static void main() { C.W(volume(10)); C.W(volume(2.5 F,8)); C.W(volume(100L,75,15)); } static int volume(int x) { return (x*x*x); //cube } static double volume(float r,int h) { return(3.14*r*r*h); //cylinder } static long volume( long l,int b,int h) { return(l*b*h); //box } 36
  • 37. Defining a class class classname { [variables declaration;] [methods declaration;] } • Class is user defined data type with a template that serves to define its properties • Class is the keyword, classname is the valid C# identifier • Everything inside [ ] is optional. 37
  • 38. Adding variables • Data is encapsulated in a class by placing data fields inside the body of the class definition. • These variables are called instance variables because they are created whenever a object of the class of instantiated. class rectangle { int length; int width; } 38
  • 39. Adding methods • A class with only data fields and no methods that operate on that data has no life. type methodname (parameter-list) { method-body; } class rectangle { int length; int width; public void getdata(int x,int y) { length=x; length=y; } } 39
  • 40. Member access modifiers • Private,Public,Protected,Internal,Protected internal • By default it is private class visiblity { public int x; internal int y; protected double d; float p; //private by default } 40
  • 41. Creating objects • Objects are created in C# using the new operator. • The new operator creates an object of the specified class and returns a reference to that object. • rectangle rect1; //declare • rec1=new rectangle(); //instantiate • rectangle()is default constructor of the class. 41
  • 42. Accessing class members • objectname.variablename; • objectname.methodname(parameter_list); • rect1.length=15; • rect1.width=10; • Constructors: • It enables an object to initialize itself when it is created. • Same name as that of the class. • Do not have any return type, not even void. 42
  • 43. Overloaded constructors • Methods have same name, different parameter list and different definitions method overloading. • Used to perform simple tasks which requires different types of parameter list. • Also known as polymorphism. • Each parameter list should be unique. • rect r1=new rect(10,20); • rect r2=new rect(10); class rectangle { public int length; public int width; public rectangle(int x,int y) { length=x; width=y; } public rectangle(int x) { length=width=x; } public int area() { return(length*width); } } 43
  • 44. Static constructors • Called before any objects of the class is created. • Used to assign initial values to static data members. class abc{ static abc(){ .. } .. } 44
  • 45. • Private constructors – All declarations must be contained in the class – Creating objects using such classes may be prevented by adding a private constructor to the class. • Copy constructors – Creates an object by copying variables from another object. • C# does not provide a copy constructor. We have to define. public item(item item) { code=item.code; price=item.price; } • Copy constructor is invoked by instantiating an object of type Item and passing it object to be copied. • Item item2=new item(item1); 45
  • 46. deconstructors • Opposite of constructors. • Name is same as that of the constructor , preceded by ~. class fun {… ~fun(){..} } • C# manages the memory dynamically and uses a garbage collector, executes all deconstructors on exit. • The process of calling a deconstructors when an object is reclaimed by the garbage collector is called finalization. 46
  • 47. This reference class integers { int x; int y; public void setxy(int x,inty) { this.x=x; this.y=y; } … } 47
  • 48. Nesting of classes public class outer { …. // members of outer class public class inner { ….//members of inner class } } 48
  • 49. Constant members • Allows declaration of data fields of a class as constant. • public const int size=100; • Member size is initialized 100 during compilation , it cannot be changed later. • Any attempt done to assign a value to it, will result in compilation error. • Const members are implicitly static. • public static const int size=100; • Will produce compile time error, we cannot declare explicitly using static 49
  • 50. read-only members • Using readonly modifier, we can set the value of the member using a constructor method, cannot be modified later. • Declared as static fields or instance fields. class numbers { public readonly int m; public static readonly int n; public numbers(int x) { m=x; } static numbers() { n=100; } } 50
  • 51. properties • Accessor methods to access the data members • Mutator method  to set the value of the data members • Drawback: • We have to code accessor methods manually • Uses should remember that they have to use accessor methods to work with data members using system; class number { private int number; public int anumber; //property { get return number; set number=value; } } class propertytest { public void static main() { number n=new number(); n.anumber=100; int m=n.anumber; Console.WriteLine(“Number=”+m); } } 51
  • 52. indexers • They are location indicators • Used to access class objects just like accessing elements in array • Useful when class is container of other classes. • The indexer takes an index argument and looks like an array • The indexer is declared using name this. • Implemented using get and set accessors for the [] operator. public double this[int idx] { get { //return desired data } set {//set desired data } } 52
  • 53. Defining an interface • it contains one or more methods, properties, indexers, events but none of them are implemented in the interface itself. interface interface_name { member declarations; } eg. interface show { void display(); } 53
  • 54. Extending an interface Interface l1 { …. } interface l2 { …. } interface l3:l2,l1 { …. } 54 Interface name2:name1 { members of name2 } • Eg: interface addition { int add(intx,int y); } interface compute:addition { int sub(int x, int y); }
  • 55. Implementing interfaces class classname :interfacename { body of classname } • Here classname implements the interfacename class a:b,l1,l2 { … } • Where B is the base class and l1,l2 are the interfaces 55
  • 56. Abstract class and interfaces interface a { void method(); } abstract class b:a { .. public abstract void method(); } 56
  • 57. Delegates • Dictionary meaning of “Delegate” means a person acting for another person. • In C# it means a method acting for another method. • It is used to invoke a method that has been encapsulated into it at time of its creation. • Has four steps – Delegate declaration – Delegate methods definition – Delegate instantiation – Delegate invocation 57
  • 58. Delegate declaration • A delegate declaration defines a class using that System.Delagate base class. • Delegate methods are any functions whose signature matches the delegate signature exactly. • modifier delegate return-type delegate-name(parameters); • Delegate may be defined in the following places – Inside a class – Outside a class – As top level object in a namespace. • Delegates are implicitly sealed. 58
  • 59. Delegate methods • Methods whose references are encapsulated into a delegate instance are known as delegate methods or callable entities. • The signature and return type of the delegate methods must exactly match the signature and return type of the delegate. • They do not care – What type of object the method is being called against. – Whether the method is static or instance method. 59
  • 60. Delegate instantiation • New delegate-type(expression) • Delegate-type is the name of the delegate declared earlier whose object is to be created. • Expression must be method name or value of delegate type. delegate int productdelegate(int x,int y); class delegate { static int product (int a,int b) return (a*b); //delegate instantiation productdelegate p=new productdelegate(product); } 60
  • 61. Delegate invocation • delegate_object(parameter_list) • If the invocation return void, the result is nothing and therefore it cannot be used as an operand of any operator. • Eg. delegate(x,y); • If a method returns a value, then it can be used as an operand of any operator. • Eg. double result= delegate(2.56,45.73); 61
  • 62. Events • An event is a delegate type class member that is used by the object or class to provide a notification to other objects that an event has occurred. • The client object can act on an event by adding an event handler to the event. • modifier event type event-name; • Modifiers can be static,virtual,override,abstarct,sealed. • Typedelegate. • Eg: public event EventHandler click; • EventHandler is a delegate and click is an event. 62