Tuesday 12 March 2013

Delegates in C#

It is also an user defined type which is used for invoking or calling the methods of a class.

A method that is defined under a class can be called in 2 different ways
  • With the help of object of a class if it is non static or name of a class if it is static.
  • By using the delegate also we can call  the method of a class even if it is static or non static.
Note: Calling the method in the 1st process is different than calling the method in the 2nd process.

Calling a method using a Delegate

       If we want to call a method using a delegate we need to adopt the following process
  • Defining a delegate:   
[<modifiers>] delegate <void/type> <Name> ([<Parameter Definition's>])

The definition of a delegate is similar to a method definition where a method will have body whereas a delegate will not have any body where we use these delegates for calling these methods.

Note: While defining a delegate make sure the I/O parameters of Delegates are same as the I/O parameters of the method we want to call with the help of a delegate.
  • As the delegate is a type, after defining a delegate to consume it we need to create an object of it and while creating the object, the method we want to call using the delegate should be passed as a parameter to the delegates constructor.
  • Now call the delegate by passing the required parameter value so that the method gets executed internally.

No comments:

Post a Comment