📒
Notes
Cloud ComputingData Science/AIGame Development
  • Home
  • Big O
  • Data Structures & Algorithms
    • Data Structures
      • Array
      • Stack
      • Queue
      • Linked List
      • Binary Tree
    • Algorithms
      • Searching
      • Sorting
      • Graphs
        • Searching
        • Minimum Spanning Tree
        • Shortest Path Algorithms
      • String Algorithms
  • Object Oriented Programming
  • Languages
    • HTML/CSS
      • CSS
    • C++
    • C#
      • Types
      • Keywords
        • Modifiers
          • Access Modifiers
        • Method Parameters
      • Operators and Expressions
      • Collections
      • Constructors
      • Delegates
      • Indexers
      • Concepts
      • Features
        • LINQ
          • Operators
          • Working with Data
          • Methods
          • Resources
        • Asynchronous Programming
        • Reflection
    • Dart
    • GraphQL
    • JavaScript
      • Variable and Parameter
      • Built-in objects
        • Array
        • Built-in Functions
      • Functions
      • Classes
      • Prototype
      • Libraries
        • jQuery
        • React
          • Components
          • State and Lifecycle
          • Hooks
            • useState
            • useEffect
          • Resources
      • Testing Framework
      • Web APIs
    • Kotlin
      • Basics
    • Python
      • Basics
      • Data Structures
      • Functions
      • Resources
        • Flask
    • SQL
      • Basics
      • Operators
      • JOINs
      • Aggregations
      • Subqueries
      • Views
      • Functions
        • Window Functions
      • Stored Procedures
      • Performance Tuning
      • Extras
    • Resources
  • 🌐Web Frameworks
    • Angular
      • Templates
      • Directives
        • Attribute Directives
        • Structural Directives
    • ASP.NET
      • Fundamentals
        • Dependency Injection
        • Middleware
        • Session & State Management
      • Web apps
        • MVC
          • Controllers
            • Filters
          • Models
            • Model Binding
            • Model Validation
          • Views
            • Tag Helpers
            • View Components
          • Features
        • Client-side development
      • Web APIs
        • Controller-based APIs
        • Minimal APIs
        • OpenAPI
        • Content Negotiation
      • SignalR
      • Host and Deploy
        • IIS
      • Security
    • Django
      • The Request/Response Cycle
    • Terminologies
      • Web Server
        • Internet Information Services
    • Resources
  • 📱App Frameworks
    • Introduction
      • Resources
    • Xamarin
      • Lifecycle
      • Custom Renderers & Effects
      • Behaviors
      • Triggers
      • Gestures
      • Commands
      • Dependency Service in XF
      • Libraries
      • Showcase
    • .NET MAUI
      • Controls
      • Navigation
      • Storage Options
  • Multi-Platform Frameworks
    • .NET
      • .NET Framework
        • ADO.NET
        • WCF
      • Fundamentals
        • Logging
        • Testing
      • Advanced
        • Asynchronous Programming
        • Parallel Programming
        • Threading
        • Memory Management
          • Garbage Collection
    • Flutter
  • Object-Relational Mappers
    • Entity Framework
      • Application Models
      • Configuration
      • Setting Up
      • Advanced
  • Databases
    • Introduction
      • DBMS Architecture
      • Normalization
      • Database Transaction Models
    • Relational Databases
      • Microsoft SQL Server
        • Basics
        • Functions
        • Stored Procedures
        • Error Handling
        • Log Shipping
        • Querying and Manipulating JSON data
        • Statements
        • Topics
        • Extras
    • Non-Relational Databases
      • MongoDB
      • Redis
        • Data Structures
        • Introduction
        • Managing Database
  • Tools
    • Version Control
      • Git
        • Setup and Config
        • Basics
          • Sharing and Updating Projects
        • Resources
      • Perforce Helix
    • GitHub
    • Powershell
  • Software Development
    • Software Development Life Cycle
    • Software Design Patterns
      • GoF Design Patterns
      • Architectural Patterns
        • MVC
        • MVVM
        • N-tier Architecture
        • Onion Architecture
        • Data Transfer Objects
      • CQRS
    • Software Design Principles
      • S.O.L.I.D. Priniciple
  • System Design
    • Topics
      • Load Balancing
  • Topics
    • JWT
    • Caching
      • Static vs Dynamic Caching
    • OSI model
      • HTTP
    • Glossary
    • API
      • SOAP
      • REST
    • Microservices
    • WebHooks
    • Practice
    • Operating Systems
      • Windows
    • Architecture
  • 🔖Bookmarks
  • 🔗Resources
Powered by GitBook
On this page
  • Types of Delegate
  • Generic Delegate
  • Things to Remember

Was this helpful?

  1. Languages
  2. C#

Delegates

  • A delegate is a type that represents references to methods with a particular parameter list and return type.

  • When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.

  • You can invoke (or call) the method through the delegate instance.

  • Delegates are used to pass methods as arguments to other methods.

  • Event Handlers are nothing more than methods that are invoked through delegates.

Types of Delegate

  • Single Delegate - used to invoke single method

  • Multicast Delegate - used to invoke multiple methods

  • Generic Delegate

    • Func Delegate

    • Action Delegate

    • Predicate Delegate

public delegate int CalculateDel(int a, int b);    // Decalaration

public class DelegateExample {
    public void Sum(int a, int b) {
        return a + b;
    }
    public void Difference(int a, int b) {
        return a - b;
    }
}

class Program {
    static void Main() {
        DelegateExample obj = new DelegateExample();
        
        // Instantiation
        CalculateDel sumDel = new CalculateDel(obj.Sum);
        CalculateDel diffDel = new CalculateDel(obj.Difference);
        
        // Invocation
        Console.WriteLine("Sum : " + sumDel(10, 5));
        Console.WriteLine("Difference : " + diffDel(10, 5));
    }
}
public delegate void CalculateDel(int a, int b);    // Decalaration

public class DelegateExample {
    public void Sum(int a, int b) {
        Console.WriteLine("Sum : " + (a + b));
    }
    public void Difference(int a, int b) {
        Console.WriteLine("Difference : " + (a - b));
    }
}

class Program {
    static void Main() {
        DelegateExample obj = new DelegateExample();
        
        // Instantiation
        CalculateDel multicastDel = new CalculateDel(obj.Sum);
        multicastDel += new CalculateDel(obj.Difference);
        
        // OR
        // CalculateDel multicastDel1 = new CalculateDel(obj.Sum);
        // CalculateDel multicastDel2 = new CalculateDel(obj.Difference);
        // CalculateDel multicastDel = multicastDel1 + multicastDel2;
        
        // Invocation
        multicastDel.Invoke(10, 5);
    }
}

Multi-cast Delegate

  • All the methods will be invoked in the same order as it is added.

  • If the delegate has return type other than void then the returned value of the last invoked method will be returned.

  • If the delegate has an out parameter then the value of the out parameter will be the value assigned by the last invoked method.

Generic Delegate

Func Delegate

  • Func delegate must return a value.

  • Func delegate can have 0 to 16 input parameters.

  • Func delegate does not allow ref and out parameters.

  • Func delegate must have 1 out parameter for the result.

int Add(int a, int b) {
    return a + b;
}

Func<int, int, int> addFuncDel = Add;    // Generic Func Delegate
int result = addFuncDel.Invoke(10, 5);
Console.WriteLine(result);

Action Delegate

  • Action delegate does not return any value.

  • Action delegate can have 0 to 16 input parameters.

  • Action delegate does not allow ref and out parameters.

  • It can be used with Anonymous method and Lambda Expression.

int Difference(int a, int b) {
    return a - b;
}

Action<int, int> diffFuncDel = Difference;    // Generic Action Delegate
int result = diffFuncDel.Invoke(10, 5);
Console.WriteLine(result);

Predicate Delegate

  • Predicate delegate takes one input parameter and boolean return type.

  • Anonymous method and Lambda Expressioin can be assigned to Predicate delegate.

bool isEven(int i) {
    if(i % 2 == 0)
        return true;
    return false;
}

Predicate<int> isEvenPredicateDel = isEven;    // Generic Predicate Delegate
bool result = isEvenPredicateDel.Invoke(100);
Console.WriteLine(result);

Things to Remember

  • Delegates are like C++ function pointers but are type safe.

  • Delegates allow methods to be passed as parameters.

  • Delegates are used in event handling for defining callback methods.

  • Delegates can be chained together i.e. these allow defining a set of methods that executed as a single unit.

  • Once a delegate is created, the method it is associated will never changes because delegates are immutable in nature.

  • Delegates provide a way to execute methods at run-time.

A publisher is an object that contains the definition of the event and the delegate.

PreviousConstructorsNextIndexers

Last updated 7 months ago

Was this helpful?