Delegates in C#
Most programmers are used to passing data in methods as input and output parameters.
Imagine a scenario where you wish to pass methods around to other methods instead of data. Amazed! Read further.
Consider a scenario where you need to make a ‘business decision’ in your program, to make a decision you need data. To get data you need to call a method. However the method name is not known at design time. It will only be known at run time.
In this case you need to pass the unknown method as a parameter. The method that you are passing in is known as a Callback function. Call back functions are pointers to methods.
.NET implements the concept of function pointers using delegates.
* Delegate wraps a method. Calling delegate results in calling the method.
* Delegate is a type of object very similar to classes.
* Delegate gives a name to a method signature.
.
Where are Delegates used?
The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place.
This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.
Starting Threads/Parallel Processing:
You defined several methods and you wish to execute them simultaneously and in parallel to whatever else the application is doing. This can be achieved by starting new threads. To start a new thread for your method you pass your method details to a delegate.
Generic Classes: Delegates are also used for generic class libraries which have generic functionality defined. However the generic class may need to call certain functions defined by the end user implementing the generic class. This can be done by passing the user defined functions to delegates.
Creating and Using Delegates:
Using delegates is a two step process-
..........1) Define the delegate to be used
..........2) Create one or more instances of the delegate
Syntax for defining a delegate:
delegate string reviewStatusofARegion();
to define a delegate we use a key word delegate followed by the method signature the delegate represents. In the above example string reviewStatusofARegion(); represents any method that returns a string and takes no parameters.
Syntax for creating an instance of the delegate:
reviewStatusofARegion = new reviewStatusofARegion(myClass.getEurope)
private string getEurope()
{
return “Doing Great in Europe”;
}
To create an instance of the delegate you call its constructor. The delegate constructor takes one parameter which is the method name.
The method signature should exactly match the original definition of the delegate. If it does not match the compiler would raise an Error.
Multicast Delegate:
Delegate wraps a method. Calling delegate results in calling the method. It is possible to wrap more than one method in a delegate. This is known as a multicast delegate.
If you make a call to a multicast delegate it will call all the functions it wraps in the order specified. Please note that functions in this case should not return any values.
Syntax for defining a delegate:
delegate void deleteRowsinTable( int Year)
Syntax for instantiating the delegate:
deleteRowsinTable Cleanup = new deleteRowsinTable(archiveCompletedTasks)
Cleanup += new deleteRowsinTable(purgeCompletedTasks)
Using Delegates in Event Handling
Events could be visualized as following:
Example: You setup a wakeup alarm in your clock for 6 a.m.
Hence you need a class/object that creates and fires an event
You need a mechanism to notify all
You need a method to listen for the notification
Finally, you need a method that does something when the notification is received.
Another example
Here is how you code for it
Create a class called Mylist
1) Declare an Event public event System.EventHandler EventName;
2) Declare a method that creates the event protected virtual void OnEventName(System.EventArgs e) 3) Fire the Event when appropriate conditions are met by calling the above method
If (condition met) {protected virtual void OnEventName(System.EventArgs e);}
Now you have a class that has the event definition, triggers an event when appropriate condition occurs and notifies every one.
Next, Create a class EventListener
1) Create a variable of type MyList
2) Create a method that shows a message box
3) Create constructor which takes a parameter of type MyList
4) In the constructor add the method you created in step 2 as an eventhandler for the event ( See Code below)
5) Add a method to remove the method from the event handler
Now you have a class that handles the event and does something when the even occurs
Next, create a class in a console application to test all of the above
1) Create an instance of the list
2) Create the event handler
3) Add an Item to the list
4) See the Results
The results shown below
Thursday, April 17, 2008
Diff between Interface and Abstract
What is an Interface?
An interface is a contract, a specification that concrete
classes MUST follow. It defines method signatures but
cannot have any implementations; the latter must be
provided by the classes that implement the interface.
C# differs from C++ in this regard because C++ lacks native
language support for interfaces. As a C++ programmers you
have to create an interface by defining an abstract class
with pure virtual methods.
what is an abstract class.................
An Abstract class lets you define some behaviors and force
your subclasses to provide others.
For example, if you have an application framework, an
abstract class may provide default services such as event
and message handling. Those services allow your application
to plug in to your application framework. However, there is
some application-specific functionality that only your
application can perform. So instead of trying to define
these behaviors, the abstract class can declare abstract
methods.
Differences between Interfaces and Abstract classes Which
we use ?
I. multiple inheritance
A class may implement several interfaces but can only
extend one abstract class.
II. default implementation
An interface cannot provide any code at all, much less
default code. An abstract class can provide complete code,
default code, and/or just stubs that have to be overridden.
III. adding functionality
If you add a new method to an interface, you must track
down all implementations of that interface in the universe
and provide them with a concrete implementation of that
method.
If you add a new method to an abstract class, you have the
option of providing a default implementation of it. Then
all existing code will continue to work without change.
IV. is-a vs -able or can-do
Interfaces are often used to describe the abilities of a
class, not its central identity, e.g. an Automobile class
might implement the Recyclable interface, which could apply
to many otherwise totally unrelated objects.
An abstract class defines the core identity of its
descendants.
********************************************************
There are lost of discussion on the internet about the
Interface vs Abstract class. Also, as base class whether we
have to use interface, abstract class or normal class.
I am trying to point out few considerations on which we can
take decision about Interface vs Abstract class vs Class.
Abstract Class vs Interface
I am assuming you are having all the basic knowledge of
abstract and interface keyword. I am just briefing the
basics.
We can not make instance of Abstract Class as well as
Interface.
Here are few differences in Abstract class and Interface as
per the definition.
Abstract class can contain abstract methods, abstract
property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but
we don?t need to put abstract and public keyword. All the
methods and properties defined in Interface are by default
public and abstract.
//Abstarct Class
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}
//Interface
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}
We can see abstract class contains private members also we
can put some methods with implementation also. But in case
of interface only methods and properties allowed.
We use abstract class and Interface for the base class in
our application.
This is all about the language definition. Now million
dollar question.
An interface is a contract, a specification that concrete
classes MUST follow. It defines method signatures but
cannot have any implementations; the latter must be
provided by the classes that implement the interface.
C# differs from C++ in this regard because C++ lacks native
language support for interfaces. As a C++ programmers you
have to create an interface by defining an abstract class
with pure virtual methods.
what is an abstract class.................
An Abstract class lets you define some behaviors and force
your subclasses to provide others.
For example, if you have an application framework, an
abstract class may provide default services such as event
and message handling. Those services allow your application
to plug in to your application framework. However, there is
some application-specific functionality that only your
application can perform. So instead of trying to define
these behaviors, the abstract class can declare abstract
methods.
Differences between Interfaces and Abstract classes Which
we use ?
I. multiple inheritance
A class may implement several interfaces but can only
extend one abstract class.
II. default implementation
An interface cannot provide any code at all, much less
default code. An abstract class can provide complete code,
default code, and/or just stubs that have to be overridden.
III. adding functionality
If you add a new method to an interface, you must track
down all implementations of that interface in the universe
and provide them with a concrete implementation of that
method.
If you add a new method to an abstract class, you have the
option of providing a default implementation of it. Then
all existing code will continue to work without change.
IV. is-a vs -able or can-do
Interfaces are often used to describe the abilities of a
class, not its central identity, e.g. an Automobile class
might implement the Recyclable interface, which could apply
to many otherwise totally unrelated objects.
An abstract class defines the core identity of its
descendants.
********************************************************
There are lost of discussion on the internet about the
Interface vs Abstract class. Also, as base class whether we
have to use interface, abstract class or normal class.
I am trying to point out few considerations on which we can
take decision about Interface vs Abstract class vs Class.
Abstract Class vs Interface
I am assuming you are having all the basic knowledge of
abstract and interface keyword. I am just briefing the
basics.
We can not make instance of Abstract Class as well as
Interface.
Here are few differences in Abstract class and Interface as
per the definition.
Abstract class can contain abstract methods, abstract
property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but
we don?t need to put abstract and public keyword. All the
methods and properties defined in Interface are by default
public and abstract.
//Abstarct Class
public abstract class Vehicles
{
private int noOfWheel;
private string color;
public abstract string Engine
{
get;
set;
}
public abstract void Accelerator();
}
//Interface
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}
We can see abstract class contains private members also we
can put some methods with implementation also. But in case
of interface only methods and properties allowed.
We use abstract class and Interface for the base class in
our application.
This is all about the language definition. Now million
dollar question.
Subscribe to:
Posts (Atom)