Function that takes another function as a parameter in C#

Asked

Viewed 702 times

4

In the language Lua has how to create a function that takes as argument another function, for example :

exemplo = function(outrafunction)
  outrafunction()
end

exemplo(function print("alguma coisa") end)

Is there any way to do it using C#?

  • I changed the title because I think it had nothing to do with the real doubt if I made a mistake. The answer solved your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would be helpful to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

3 answers

5

Your syntax is wrong, but okay.

In C# would be:

using System;
using static System.Console;

public class Program {
    public static void Main() => Exemplo(() => WriteLine("alguma coisa"));
    public static void Exemplo(Action outraFunction) => outraFunction();
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

It’s essentially a different syntax, but the mechanism is identical.

0

Is it possible that this action is of the bool type ? Every time I try to make that change : "private void BuscarComprasASSD(string conta, Action Buscar, Action<bool> condicao )"

This error appears:

 não há argumento fornecido que corresponde ao parâmetro formal necessário "obj" de Action<bool>

0

If you want a function to be passed by parameter in a simple way use Action or Func. The difference between the two is that Action is void type. With Func you can have a Return type, and up to 16 input parameters. In the following example I used an Action and an Func to invoke a function but if the function can return a value.

If you want to have a wider view you can see how the delegates.

 public static void Main()
{
  Exemplo(() =>  IsLeapYear());
  Exemplo2(() => IsLeapYear());
  bool x = Exemplo3(()=> IsLeapYear());
  bool y = Exemplo3(() => IsLeapYear( DateTime.Now.Year));
}

public static void Exemplo(Action outraFuncao) => outraFuncao();
public static void Exemplo2(Func<bool> outraFuncao) => outraFuncao();
public static bool Exemplo3(Func<bool> outraFuncao) => outraFuncao();


private static bool IsLeapYear() => DateTime.IsLeapYear(DateTime.Now.Year);
private static bool IsLeapYear(int year) => DateTime.IsLeapYear(year);

You can still see this answer that explains functions and actions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.