C
C#15mo ago
moon

❔ Action and Callback

Action<Action<int, string, bool>> configureDisplayInfo = (callback) =>
{
int age = 30;
string name = "Alice";
bool isActive = true;

callback(age, name, isActive);
};

Action<int, string, bool> displayInfo = (age, name, isActive) =>
{
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Is Active: {isActive}");
};

configureDisplayInfo(displayInfo);
Action<Action<int, string, bool>> configureDisplayInfo = (callback) =>
{
int age = 30;
string name = "Alice";
bool isActive = true;

callback(age, name, isActive);
};

Action<int, string, bool> displayInfo = (age, name, isActive) =>
{
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Is Active: {isActive}");
};

configureDisplayInfo(displayInfo);
We are passing a function named "callback" as if it were a variable as a parameter, and then we are calling it as if we had previously called the function by saying "callback(age, ...)". How does this process work, how do the codes work step by step?
6 Replies
Angius
Angius15mo ago
It just kinda does. In C#, like in many other languages, you can pass pointers to functions around This is no different Whether you pass an anonymous function (Action<>, Func<>, delegate) or an actual method And you don't pass it "as if it was a variable" because it is, in fact, stored in that variable Or at least the reference to it
MODiX
MODiX15mo ago
Angius
REPL Result: Success
Action<string> cwl = Console.WriteLine;
cwl("Hello world!");
Action<string> cwl = Console.WriteLine;
cwl("Hello world!");
Console Output
Hello world!
Hello world!
Compile: 645.382ms | Execution: 78.123ms | React with ❌ to remove this embed.
moon
moonOP15mo ago
When the function is invoked, it happened like this, right? And lastly, the relevant function became this: Instead of callback(age, name, isActive) being at runtime, it became displayInfo(age, name, isActive)
Angius
Angius15mo ago
Like in case of any other parameter, yes
moon
moonOP15mo ago
Thank you a lot, I understood
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server