0
0
C Sharp (C#)programming~3 mins

Why Action delegate type in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could treat actions like simple objects you can pass and run anywhere?

The Scenario

Imagine you want to run different small tasks like printing a message or updating a score, but you have to write separate methods and call them manually every time.

The Problem

This manual way means writing lots of extra code, repeating yourself, and it's easy to make mistakes by calling the wrong method or forgetting to call one.

The Solution

The Action delegate type lets you store and pass around methods as simple variables, so you can run any task flexibly without rewriting or tightly coupling your code.

Before vs After
Before
void PrintHello() { Console.WriteLine("Hello"); }
PrintHello();
After
Action greet = () => Console.WriteLine("Hello");
greet();
What It Enables

You can easily assign, pass, and run different actions dynamically, making your code cleaner and more flexible.

Real Life Example

In a game, you can assign different actions to buttons like jump, shoot, or run without writing separate methods for each button press everywhere.

Key Takeaways

Action delegate stores methods as variables.

It reduces repetitive code and errors.

It makes running tasks flexible and dynamic.