What is Delegate in .NET Explain with an Example – Programming, Pseudocode Example, C# Programming Example

What is Delegate in .NET Explain with an Example

A delegate is an object that can refer to a method. It means that it can hold a reference to a method. The method can be called through this reference or we can say that a delegate can invoke the method to which it refers. The same delegate can be used to call different methods during the runtime of a program by simply changing the method to which the delegate refers. The main advantage of a delegate is that it invokes the method at run time rather than compile time. A delegate type is declared using the keyword delegate. Delegate types are derived from the Delegate class.

.NET framework provides several different delegates that provides flexible options

  • Action<T> : Accepts single parameter and returns no value
  • Func<T,TResult> : Accepts a single parameter and returns a value of type TResult.

C# Delegate Example

Example Program for Built-in Delegates in .NET

Example: Following is the example of creating delegates in the c# programming language.

Example: Declaring and Implementing a Delegate: SimpleDelegate.cs

Example 3: Following is the example of implementing a multicast delegate to hold the reference of multiple methods with "+" operator in c# programming language.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: