Reputation: 3127
After googling it doesn't look promising, but I'm wondering if there is some way of aliasing or typedef'ing when using Action<T>
or Func<in T, out TResult>
in C#?
I've already seen Equivalent of typedef in c#, which says that within one compile scope you can use the using
construct for some cases, but that doesn't seem to apply to Action
's and Func
's as far as I can tell.
The reason I want to do this is that I want an action to be used as a parameter to several functions, and if I, at some point in time, decide to change the action it's a lot of places to change both as parameter types and as variable types.
?typedef? MyAction Action<int, int>;
public static SomeFunc(WindowClass window, int number, MyAction callbackAction) {
...
SomeOtherFunc(callbackAction);
...
}
// In another file/class/...
private MyAction theCallback;
public static SomeOtherFunc(MyAction callbackAction) {
theCallback = callbackAction;
}
Are there some construct to use, which can define the MyAction
as indicated in the code segment?
Upvotes: 10
Views: 5384
Reputation: 3127
After some more searching, it seems as though delegate
's comes to the rescue (see Creating delegates manually vs using Action/Func delegates and A:
Custom delegate types vs Func and Action). Please comment as to why this is not a solution or possible pitfalls.
With delegates I can rewrite the first line the given code example:
public delegate void MyAction(int aNumber, int anotherNumber);
// Keep the rest of the code example
// To call one can still use anonymous actions/func/...
SomeFunc(myWindow, 109, (int a, int b) => Console.Writeline);
Upvotes: 10
Reputation: 1237
using System;
namespace Example
{
using MyAction = Action<int>;
internal class Program
{
}
private void DoSomething(MyAction action)
{
}
}
Upvotes: 6