Built-in Delegates in C# β Easy Explanation with Examples
Introduction
Tired of writing long delegate definitions? π΅ Wish there was an easier way to use delegates in C#? Well, youβre in luck! π
C# provides Built-in Delegates, which make life so much easier. You donβt need to declare custom delegates anymore. Just use the ready-made ones and save time!
By the end of this lesson, youβll be a pro at using Built-in Delegates in C# with real-world examples! Letβs go! π
π What You Are Going to Learn in This Lesson?
βοΈ What are Built-in Delegates in C#?
βοΈ Why do we need them?
βοΈ How to use Action
, Func
, and Predicate
?
βοΈ Real-world scenario example
βοΈ Multiple coding examples
βοΈ Step-by-step explanation with output
What Are Built-in Delegates in C#?
A delegate is just a reference to a method. But declaring delegates every time is boring. π΄
Thatβs why C# gives us three built-in delegates:
β‘οΈ Action β For methods that donβt return a value.
β‘οΈ Func β For methods that return a value.
β‘οΈ Predicate β For methods that return bool
.
No need to write delegate definitions anymore! Just use these ready-made ones! π₯³
Syntax of Built-in Delegates in C#
Action<int> myAction; // Stores a method with 1 int parameter, returns nothing
Func<int, string> myFunc; // Stores a method with 1 int parameter, returns a string
Predicate<int> myPredicate; // Stores a method with 1 int parameter, returns bool
Example 1: Using Action
Delegate
π Use Action<T>
when you donβt need a return value.
π‘ Think of Action<T>
like a messenger. It takes input, performs an action, but doesnβt return anything.
using System;
class Program {
static void PrintMessage(string msg) {
Console.WriteLine(msg);
}
static void Main() {
Action<string> action = PrintMessage; // Using Action delegate
action("Hello from Action delegate!");
}
}
π Output:
Hello from Action delegate!
π Step-by-Step Explanation:
- Step 1: Declared an
Action<string>
delegate, which means it stores a method that takes astring
and returnsvoid
. - Step 2: Assigned the
PrintMessage
method to theaction
delegate. - Step 3: Called
action("Hello...")
, which executedPrintMessage()
.
π Result? The message got printed! π
Β
π Why Use Action<T>
?
β
No need to define custom delegates. Saves time! β³
β
Makes code reusable. Just assign different methods when needed! π
β
Perfect for logging, printing messages, notifications, etc. π’
Β
π Real-World Use Case?
Imagine a notification system where Action<string>
is used to send alerts via Email, SMS, or Push Notification dynamically! π
Example 2: Using Func
Delegate
π Use Func<T, TResult>
when you need a return value.
π‘ Think of Func<T, TResult>
like a calculator. It takes input, performs a calculation, and returns a result.
using System;
class Program {
static int DoubleNumber(int num) {
return num * 2;
}
static void Main() {
// β
Func delegate: Takes an int, returns an int
Func<int, int> func = DoubleNumber;
// β
Calling the delegate and storing the result
int result = func(10);
Console.WriteLine("Double of 10 is: " + result);
}
}
π Output:
Double of 10 is: 20
π Step-by-Step Explanation:
- Step 1: Declared a
Func<int, int>
delegate, which means it takes anint
as input and returns anint
as output. - Step 2: Assigned the
DoubleNumber
method to thefunc
delegate. - Step 3: Called
func(10)
, which executedDoubleNumber(10)
and returned20
. - Step 4: Printed the result.
π Result? The number got doubled! π
Β
π Why Use Func<T, TResult>
?
β
Eliminates the need for custom delegates. Saves time! β³
β
Perfect for mathematical operations, data transformations, filtering, etc. π’
β
Enhances code reusability & readability! π
Β
π Real-World Use Case?
Imagine a discount calculator where Func<decimal, decimal>
is used to calculate the final price after applying a discount dynamically! π
Example 3: Using Predicate
Delegate
π Use Predicate<T>
when you need a bool
return value.
π‘ Think of Predicate<T>
like a security check. It takes input, evaluates a condition, and returns true or false.
using System;
class Program {
static bool IsEven(int num) {
return num % 2 == 0;
}
static void Main() {
Predicate<int> predicate = IsEven; // Using Predicate delegate
bool result = predicate(10);
Console.WriteLine("Is 10 even? " + result);
}
}
π Output:
Is 10 even? True
π Step-by-Step Explanation:
- Step 1: Declared a
Predicate<int>
delegate, which means it takes anint
as input and returns abool
as output. - Step 2: Assigned the
IsEven
method to thepredicate
delegate. - Step 3: Called
predicate(10)
, which executedIsEven(10)
and returnedtrue
. - Step 4: Printed the result.
π Result? It correctly identified that 10
is even! π
Β
π Why Use Predicate<T>
?
β
Perfect for filtering data based on conditions!
β
Commonly used in List<T>.Find()
and LINQ queries.
β
Enhances code reusability & readability!
Β
π Real-World Use Case?
Imagine a student grading system where Predicate<int>
is used to check if a student has passed or failed based on a minimum score! π
Why Are Built-in Delegates Important?
β They save time! No need to declare custom delegates.
β They make code cleaner! Just use Action
, Func
, or Predicate
.
β They work well with LINQ and collections!
Real-World Example: Filtering a List π
Imagine you have a list of numbers, and you want to filter only even numbers. You can use Predicate<int>
instead of writing long loops!
using System;
using System.Collections.Generic;
class Program {
static bool IsEven(int num) {
return num % 2 == 0;
}
static void Main() {
List<int> numbers = new List<int> {1, 2, 3, 4, 5, 6, 7, 8};
List<int> evenNumbers = numbers.FindAll(IsEven); // Using Predicate
Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers));
}
}
π Output:
Even numbers: 2, 4, 6, 8
π Explanation:
β FindAll(IsEven)
filters only even numbers.
β No need to write long loops! π
Another Example: Logging Messages π
Use Action<string>
to log messages without repeating code!
using System;
class Logger {
public static void Log(string message) {
Console.WriteLine("[LOG]: " + message);
}
}
class Program {
static void Main() {
Action<string> logAction = Logger.Log; // Using Action delegate
logAction("Application started!");
logAction("User logged in.");
}
}
π Output:
[LOG]: Application started!
[LOG]: User logged in.
π Explanation:
β Action<string>
stores the Log()
method.
β The same delegate is reused for logging different messages.
Conclusion
Built-in Delegates in C# make coding simple and efficient.
β‘οΈ Use Action<T>
when no return value is needed.
β‘οΈ Use Func<T, TResult>
when a return value is needed.
β‘οΈ Use Predicate<T>
when returning bool
.
Now go ahead and try them in your projects! Happy coding! π
Β
Next What?
Woohoo! π Now you know Built-in Delegates in C# like a pro! π
π Next, you will learn about OOPs β Properties and Indexers in C#! Stay excited! π