C # Delegate

Source: Internet
Author: User

Delegate is a type that represents a reference to a method with a specific argument list and return type. when you instantiate a delegate, you can associate its instance with any method that has a compatible signature and return type. you can invoke a method from a delegate instance.

The event handler is the method that is called through the delegate. You can create a custom method that can be called by a class (such as a Windows control) when a particular event occurs. The following example shows a delegate declaration:

 Public Delegate int Performcalculation (intint y);

Any method that matches a delegate type in any accessible class or struct can be assigned to a delegate. the method can be either a static method or an instance method. This makes it possible to programmatically change method calls and to insert new code into existing classes.

note

But in the context of the delegate, the signature includes the return value.

The ability to reference a method as a parameter makes the delegate an ideal choice for defining a callback method. For example, a reference to a method that compares two objects can be passed as a parameter to the sorting algorithm. because the comparison code is in a separate process, the sorting algorithm can be written in a more common way.

Delegate Overview

Delegates have the following properties:

  • Delegates are similar to C + + function pointers, but they are type-safe.

  • A delegate allows a method to be passed as a parameter.

  • Delegates can be used to define callback methods.

  • Delegates can be chained together; For example, multiple methods can be called on an event.

  • method does not have to match the delegate type exactly.

C # Delegate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.