A Developer Journey who codes for fun

Daily Dose Of Code

  • Home
  • Dot.Net Basics
    • .Net Basics
      • CTS
      • CLS
      • CLR
      • Strong Vs Weak Ref
      • .Net Framework
      • What is Manifest
    • Memory Management
      • Garbage Collection 1
      • Garbage Collection 2
      • Circular Reference
  • C Sharp
    • Abstract Class in C#
    • Interfaces in C#
    • Value type by Val and By Ref
    • Var keyword
    • Null Coalescing Operator
    • Buit-in code snippets
  • OOPS
    • Abstraction and Encapsulation
    • Polymorphism
    • Inheritence
    • Aggregation
  • Threading
    • Delegates
      • Calling Delegate using Invoke, BeginInvoke
      • Multicast Delegate
      • Exception Handling in Multicast Delegate
      • Action
      • Predicate
      • Func
    • Synchronization
    • Thread Pool
    • Exception Handling
    • TPL
  • Design Pattern
    • Creational Patterns
      • Singleton Pattern
      • Factory Pattern
      • Abstract Factory Pattern
      • Prototype Pattern
      • Builder Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Proxy Pattern
      • Facade Pattern
      • Decorator Pattern
      • Flyweight Pattern
    • Behavioral Patterns
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
      • Visitor Pattern
      • Chain Of Responsibility Pattern
      • Template Pattern
  • Data Structures
    • Generic List in C#
    • 2d array to 1d array
    • 3d arrayto 1d array
    • Linked List
      • Singly Linked List in C#
    • Queue
      • Dummy Data 1
    • Stack
      • Dummy Data 2
    • Tree
      • Dummy Data 3
    • Graph
      • Dummy Data 4
  • WCF
    • WCF Service using VS 2015
  • Scripts
    • Chrome Extensions
      • Create a Chrome Extension
      • Facebook autologout script
      • Gmail autologout script

Delegates in C Sharp

 Unknown     1:35 PM     C#, Threading     17 comments   

A Delegate is a type variable that holds the reference to a method. Delegates are similar to Pointer to functions in C and C++

When we create a delegate then we can assign a method to delegate instance according to its signature and we can change the reference at run time. After assigning the method we can call this method using delegate instance.

Note - Your method signature and return type must match with Delegate

Why do we need to create a Delegate ?
  • Delegate Invoke method at run time.
  • Delegate can be used for callback methods.
  • Delegates can invoke multiple methods on a single event. So this is useful when we have to give multiple implementation of a single method.
  • When do you want to restrict access to caller then we can expose a delegate.
Now How can we create a Delegate ?

public delegate int MyPointer(int x, int y);

AccessModifier, delegate type , return type DelegateName(Delegate params)

This is how we can create a Delegate. Now the point is how can we create a Delegate instance and add methods at run time.


So let's check out this example - 


public class MyDelegate
    {
        public delegate int MyPointer(int x, int y);

        /// <summary>
        /// CTOR
        /// </summary>
        public MyDelegate() { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <returns></returns>
        public MyPointer MyOperation(int operation)
        { 
            MyPointer objPointer = null;
            if( operation == 1)
            {
                objPointer = Add;
            }
            else if (operation == 2)
            {
                objPointer = Sub;
            }
            else if (operation == 3)
            {
                objPointer = Mul;
            }
            else if (operation == 4)
            {
                objPointer = Div;
            }

            return objPointer;
        }

        private int Add(int x, int y)
        {
            return x + y;
        }

        private int Sub(int x, int y)
        {
            return x - y;
        }

        private int Mul(int x, int y)
        {
            return x * y;
        }

        private int Div(int x, int y)
        {
            return x / y;
        }
    }



How MainMethod will call delegate and execute the methods - Let's have a look


static MyDelegate objDel;

        static void Main(string[] args)
        {
            objDel = new MyDelegate();
            Delgateinvoke();
        }




private static void Delgateinvoke()
        {
            //Way 1
            int num = objDel.MyOperation(1).Invoke(4, 5);

            //Way2
            MyDelegate.MyPointer delegateInstance = objDel.MyOperation(1);
            delegateInstance.Invoke(4, 5);

            Console.WriteLine(num.ToString());
        }

So here we created instance of a class MyDelegate and call the method MyOperation.It returns a delegate instance now we call the invoke method of delegate.

Looks Cool..


Now the question comes What is this Invoke ? See below example -














So delegate has these mentioned methods for instantiation. Currently I am using Invoke method to instantiate the delegate. When we say instantiate it means delegate call the same method which we attach.

Let's talk about these methods mentioned above -

BeginInvoke - Executes asynchronously on a pooled thread (Thread pooling or TPL)

Invoke - Delegate execute synchronously on the same thread.

DynamicInvoke- Delegate execute synchronously but as name says dynamic, you pass the parameter to function does boxing and unboxing at runtime. It requires an object array to execute the method. Avoid this as it is Damn Slow.

GetInvocationList -  This Fetches all the method info you associated with the Delegate. So it is useful when you want to execute delegate according to your need. You can fetch the info and invoke accordingly. We will discuss this in next articles.

Types Of Delegates :
  • Single Delegate
  • Multi Cast Delegate
  • Readymade Delegates - Func, Action and Predicate

In this article we talked about single delegate . In Next Article we will talk about Multi Cast Delegate and Readymade Delegates in C#


Hope you enjoyed reading the article. Please inbox me in case of any confusion.
Happy Coding :)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Exception Handling in Multicast Delegate ? Hello Guys, In this article we will discuss about how to handle exception in multicast delegate ? In case you want to understand Delegate and Multic… Read More
  • Multicast Delegate in C# Hello Everyone, I talked about delegate in my last article. In this article we will talk about multicast delegate. A Delegate is a type variable th… Read More
  • Action Delegate in C# Hello everyone, in this article we will talk about “Action” a readymade delegate. Action is just another delegate that takes some parameters and doe… Read More
  • Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ? Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate. In this article we will discuss what are th… Read More
  • Func Delegate in C# Hello Everyone, In this article we will talk about Func< in T, out TResult>  Delegate.   It is another readymade delegate that provi… Read More
Newer Post Older Post Home

17 comments:

  1. UnknownNovember 1, 2015 at 5:17 AM

    Great post. Let more posts and information flow in more frequently. :)

    ReplyDelete
    Replies
      Reply
  2. AnonymousFebruary 3, 2022 at 11:03 PM

    A Beginner's Guide to Casino Games - YouTube
    If you want to learn how to play casino games for money online, and youtube mp3 start to enjoy online gambling, then you've come to the right place.

    ReplyDelete
    Replies
      Reply
  3. NightfallPhoenixRiderSeptember 29, 2023 at 5:22 PM

    Bursa
    Mersin
    izmir
    Rize
    Antep
    PDBL

    ReplyDelete
    Replies
      Reply
  4. InfinityPioneerNinja9000October 4, 2023 at 2:57 PM

    kars
    sinop
    sakarya
    ankara
    çorum
    OWO

    ReplyDelete
    Replies
      Reply
  5. Çisil1October 4, 2023 at 11:20 PM

    yozgat
    sivas
    bayburt
    van
    uşak
    F3TKDC

    ReplyDelete
    Replies
      Reply
  6. Mert7October 21, 2023 at 1:51 AM

    Bolu Lojistik
    Mardin Lojistik
    Kocaeli Lojistik
    Diyarbakır Lojistik
    İstanbul Lojistik
    N5S

    ReplyDelete
    Replies
      Reply
  7. GalacticCipheressOctober 22, 2023 at 11:52 AM

    istanbul evden eve nakliyat
    balıkesir evden eve nakliyat
    şırnak evden eve nakliyat
    kocaeli evden eve nakliyat
    bayburt evden eve nakliyat
    F0YRDK

    ReplyDelete
    Replies
      Reply
  8. ElectricGoddess12ATOctober 22, 2023 at 3:50 PM

    sivas evden eve nakliyat
    erzurum evden eve nakliyat
    bitlis evden eve nakliyat
    mardin evden eve nakliyat
    rize evden eve nakliyat
    İDB63İ

    ReplyDelete
    Replies
      Reply
  9. 56503ShaneE390ANovember 9, 2023 at 3:32 AM

    71E81
    Karapürçek Parke Ustası
    Zonguldak Evden Eve Nakliyat
    Yenimahalle Boya Ustası
    Edirne Lojistik
    Erzincan Lojistik
    Mamak Boya Ustası
    Sivas Parça Eşya Taşıma
    Kocaeli Şehir İçi Nakliyat
    Mersin Evden Eve Nakliyat

    ReplyDelete
    Replies
      Reply
  10. A3A4FEricaB1808November 9, 2023 at 3:33 AM

    59313
    Poloniex Güvenilir mi
    Ünye Marangoz
    Bursa Şehir İçi Nakliyat
    Kars Şehir İçi Nakliyat
    Erzurum Lojistik
    Burdur Evden Eve Nakliyat
    Batıkent Parke Ustası
    Sakarya Lojistik
    Van Parça Eşya Taşıma

    ReplyDelete
    Replies
      Reply
  11. 7CED8Yasmin689ADNovember 10, 2023 at 1:03 AM

    DEE71
    Çerkezköy Mutfak Dolabı
    Kırşehir Şehir İçi Nakliyat
    Antalya Lojistik
    Silivri Fayans Ustası
    Sakarya Evden Eve Nakliyat
    Edirne Lojistik
    Mardin Parça Eşya Taşıma
    Amasya Evden Eve Nakliyat
    Konya Lojistik

    ReplyDelete
    Replies
      Reply
  12. 2B5CDAniyaCF391November 21, 2023 at 9:22 AM

    BB23B
    order testosterone propionat
    order testosterone enanthate
    Elazığ Evden Eve Nakliyat
    Silivri Boya Ustası
    Kütahya Evden Eve Nakliyat
    buy testosterone enanthate
    Yozgat Evden Eve Nakliyat
    order sarms
    Çerkezköy Evden Eve Nakliyat

    ReplyDelete
    Replies
      Reply
  13. 06A83Jairo2DB01January 6, 2024 at 8:56 AM

    AD53E
    Jns Coin Hangi Borsada
    Bitcoin Nasıl Kazılır
    Parasız Görüntülü Sohbet
    Alya Coin Hangi Borsada
    Bitcoin Kazma Siteleri
    Coin Üretme
    Referans Kimliği Nedir
    Bitcoin Nasıl Üretilir
    Twitter Beğeni Satın Al

    ReplyDelete
    Replies
      Reply
  14. C0F5EWesley9F3B7January 7, 2024 at 12:08 PM

    AC45B
    Bitcoin Mining Nasıl Yapılır
    Binance Referans Kodu
    Vector Coin Hangi Borsada
    Kaspa Coin Hangi Borsada
    Big Wolf Coin Hangi Borsada
    Referans Kimliği Nedir
    Azero Coin Hangi Borsada
    Mexc Borsası Güvenilir mi
    Kwai Takipçi Hilesi

    ReplyDelete
    Replies
      Reply
  15. AnonymousJanuary 31, 2025 at 8:24 AM

    DC33EF1170
    mobil odeme ile instagram takipci alma

    ReplyDelete
    Replies
      Reply
  16. AnonymousFebruary 5, 2025 at 8:12 PM

    AB2AA5CF74
    insta takipçi
    Razer Gold Promosyon Kodu
    Osm Promosyon Kodu
    Kazandırio Kodları
    PK XD Elmas Kodu
    MLBB Hediye Kodu
    Roblox Şarkı Kodları
    PK XD Elmas Kodu
    Hay Day Elmas Kodu

    ReplyDelete
    Replies
      Reply
  17. AnonymousFebruary 25, 2025 at 5:24 PM

    0FE99A5046
    telegram coin grupları güvenilir mi
    butona bas coin kazan
    coin madenciliği
    coin kazandıran oyunlar
    telegram coin kasma nedir

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

About The Author

Unknown
View my complete profile

Total Pageviews

84613

Popular Posts

  • Clr - Common Language Runtime
    .Net framework provides a run time environment - CLR. Common language runtime takes the IL code from the compiler( language specific) and p...
  • Auto logout chrome extension for Gmail
    Hello Friends, In the last article we learned to create a sample chrome extension. Here we are going to create auto logout Gmail script as...
  • Predicate delegate in C#
    Hello Everyone, In the article we will talk about Predicate delegate. Predicate is also a delegate which encapsulate a method that takes...
  • .Net Framework overview
    Hello friends : Here i am writing my first article on .Net framework anyways....So the question is What is .Net Framework ? The .Net fram...
  • Nagarro Placement Papers..
    Ques.1 :- Seat Reservation prog for the theatre. Write a function for seat allocation for the movie tickets. Total no of seats available are...
  • What does it mean by disconnected data access architecture of ADO.Net?
    ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the databa...
  • Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ?
    Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate. In this article we will discuss w...
  • C code to Check the string has valid identifier or not in.
    #include #include #include char keyword[][10]={"auto","break","case","char","const","...
  • Garbage Collection - Automatic Memory Management Part II
    Welcome friends in the second article of Garbage Collection. Those who have missed the first one can visit here . So in this article i will...
  • Delegates in C Sharp
    A Delegate is a type variable that holds the reference to a method. Delegates are similar to Pointer to functions in C and C++ When we...

Blog Archive

  • ►  2016 (4)
    • ►  September (2)
      • ►  Sep 03 (2)
    • ►  August (1)
      • ►  Aug 28 (1)
    • ►  April (1)
      • ►  Apr 24 (1)
  • ▼  2015 (12)
    • ▼  September (10)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 27 (2)
      • ▼  Sep 26 (3)
        • Calling the Delegates using Invoke(), BeginInvoke(...
        • Delegates in C Sharp
        • Interfaces in C#
      • ►  Sep 20 (1)
      • ►  Sep 19 (1)
    • ►  August (1)
      • ►  Aug 16 (1)
    • ►  March (1)
      • ►  Mar 31 (1)
  • ►  2013 (10)
    • ►  June (1)
      • ►  Jun 16 (1)
    • ►  April (1)
      • ►  Apr 21 (1)
    • ►  February (8)
      • ►  Feb 18 (3)
      • ►  Feb 17 (2)
      • ►  Feb 16 (2)
      • ►  Feb 15 (1)
  • ►  2012 (1)
    • ►  May (1)
      • ►  May 27 (1)
  • ►  2010 (22)
    • ►  October (14)
      • ►  Oct 21 (1)
      • ►  Oct 06 (12)
      • ►  Oct 04 (1)
    • ►  April (2)
      • ►  Apr 22 (1)
      • ►  Apr 16 (1)
    • ►  March (1)
      • ►  Mar 30 (1)
    • ►  January (5)
      • ►  Jan 08 (3)
      • ►  Jan 01 (2)
  • ►  2009 (110)
    • ►  December (8)
      • ►  Dec 18 (2)
      • ►  Dec 05 (1)
      • ►  Dec 04 (5)
    • ►  November (1)
      • ►  Nov 27 (1)
    • ►  October (14)
      • ►  Oct 09 (4)
      • ►  Oct 07 (1)
      • ►  Oct 06 (3)
      • ►  Oct 05 (3)
      • ►  Oct 01 (3)
    • ►  September (17)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 25 (1)
      • ►  Sep 24 (1)
      • ►  Sep 17 (2)
      • ►  Sep 15 (3)
      • ►  Sep 11 (2)
      • ►  Sep 09 (3)
      • ►  Sep 08 (2)
    • ►  August (31)
      • ►  Aug 31 (1)
      • ►  Aug 27 (3)
      • ►  Aug 26 (1)
      • ►  Aug 25 (2)
      • ►  Aug 24 (1)
      • ►  Aug 22 (2)
      • ►  Aug 21 (3)
      • ►  Aug 20 (2)
      • ►  Aug 19 (3)
      • ►  Aug 18 (1)
      • ►  Aug 16 (1)
      • ►  Aug 12 (2)
      • ►  Aug 11 (1)
      • ►  Aug 10 (3)
      • ►  Aug 07 (4)
      • ►  Aug 06 (1)
    • ►  July (24)
      • ►  Jul 25 (4)
      • ►  Jul 24 (20)
    • ►  April (15)
      • ►  Apr 10 (3)
      • ►  Apr 07 (9)
      • ►  Apr 06 (3)

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments
copyright @ TechGiant 2015. Powered by Blogger.

Disclaimer

This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Followers

Copyright © 2025 A Developer Journey who codes for fun | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com