0

I want to pass a method with a parameter in a parameter like this. But it still got error and i didn't know what to do.

void WriteInScreen(string text){
    Console.WriteLine(text);
}
void WriteInScreen10Times(string text){
    for (int i = 1; i <= 10; i++){
        Console.WriteLine(text);
    }
}
void CallWriteInScreen(Action Method) {
    Method();
}
void StartCall(){
    //Error: Argument 2: Can't not convert from void to System.Action
    CallWriteInScreen(WriteInScreen("Hello!"));
    CallWriteInScreen(WriteInScreen10Time("Hi!"));
}

This is just my test code, i need to solve this to continue develop my program.

2 Answers2

1

CallWriteToScreen only accepts a delegate that accepts no parameters and produces no result (a.k.a an Action). Not sure whether you want to create a family of CallWriteToScreen methods that accept parameterized Actions:

void CallWriteInScreen(Action Method) {
    Method();
}
void CallWriteInScreen<T1>(Action<T1> Method, T1 arg1) {
    Method(arg1);
}
void CallWriteInScreen<T1, T2>(Action<T1, T2> Method, T1 arg1, T2 arg2) {
    Method(arg1, arg2);
}
void StartCall(){
    CallWriteInScreen(WriteInScreen, "Hello!");
    CallWriteInScreen(WriteInScreen10Time, "Hi!");
}

or just want to wrap the eventual method call up:

void StartCall(){
    CallWriteInScreen(() => WriteInScreen("Hello!"));
    CallWriteInScreen(() => WriteInScreen10Time("Hi!"));
}
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
0

you can not do this

CallWriteInScreen(WriteInScreen10Time("Hi!")); 

because the method you defined: WriteInScreen10Time("Hi!") returns void so you would be passing void to the method CallWriteInScreen which expects an Action as paramter

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97