Delegates in C #-an introduction: English)

Source: Internet
Author: User

Introduction
I assume that most people who want to learn C # are C/C ++ programmers. thus I believe that they will be looking for features in C # which are analogous to some C/C ++ feature they were quite fond. and one of my favorite features about good old C was function pointers. those of you who haven' t used function pointers missed out on the fun. well C # does have something that can be used where we used to use function pointers. actually they do a lot more than function pointers used to do. they are called delegates. as is usual with me, I'll try and demonstrate the use of delegates through commented, sample programs that are small, simple and hopefully easy to understand.
Program 1
In this program we'll see how delegates are used to encapsulate a reference to a method in a delegate object. as you can see we can declare delegates in a namespace and thus delegates are retriable among classes. you can also see that we can associate a delegate variable with both static and instance member functions.
Using System;
// Declare our delegate type
Public delegate void dgate ();
Class nish
{
Public static void Main ()
{
Test t1 = new test ();
// Create a new delegate object and associate it
// With the function abc in class test
Dgate d1 = new dgate (t1.abc );
D1 (); // call the delegate

// Now associate the delegate object
// The function xyz in class test
D1 = new dgate (t1.xyz );
D1 (); // call the delegate

Related Article

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.