Skip to content

Commit 9ace7e6

Browse files
ClémentClément
authored andcommitted
Adding simple example of actions.
1 parent 1228ecf commit 9ace7e6

3 files changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
using System;
2+
3+
public static class CallingAction
4+
{
5+
public static void Demo(Action actionP)
6+
{
7+
Console.WriteLine("Now calling action: ");
8+
actionP();
9+
Console.WriteLine("Done calling action.");
10+
}
11+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System;
2+
3+
public static class ExampleActions
4+
{
5+
public static void Test()
6+
{
7+
Console.WriteLine("Test");
8+
}
9+
public static void Display(int i)
10+
{
11+
Console.WriteLine(i);
12+
}
13+
}
14+
15+
public static class ExampleActions<T>
16+
{
17+
public static void DisplayArray(T[] arrayP)
18+
{
19+
for (int i = 0; i < arrayP.Length; i++)
20+
{
21+
Console.WriteLine(arrayP[i]);
22+
}
23+
}
24+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using System;
2+
3+
class Program
4+
{
5+
static void Main()
6+
{
7+
// We can call our
8+
// "Test" method directly:
9+
ExampleActions.Test();
10+
11+
// Or we can store it
12+
// in a variable and then call it.
13+
14+
/* An action is a
15+
* method that has no parameters and
16+
* does not return a value.
17+
* https://learn.microsoft.com/en-us/dotnet/api/system.action?view=net-9.0
18+
*/
19+
20+
Action test_variable = ExampleActions.Test;
21+
test_variable();
22+
23+
// Similarly with arguments:
24+
ExampleActions.Display(3);
25+
Action<int> display_variable = ExampleActions.Display;
26+
display_variable(10);
27+
28+
// We can even have action
29+
// from class that uses generic
30+
// type parameters.
31+
32+
int[] arrayT = { 20, 30, 40 };
33+
ExampleActions<int>.DisplayArray(arrayT);
34+
35+
Action<int[]> display_array_variable = ExampleActions<int>.DisplayArray;
36+
display_array_variable(arrayT);
37+
38+
//
39+
CallingAction.Demo(ExampleActions.Test);
40+
}
41+
}

0 commit comments

Comments
 (0)