C# Passing Function as Argument
Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}
Pass Method as Parameter using C#
You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:
public class Class1
{
public int Method1(string input)
{
//... do something
return 0;
}
public int Method2(string input)
{
//... do something different
return 1;
}
public bool RunTheMethod(Func<string, int> myMethodName)
{
//... do stuff
int i = myMethodName("My String");
//... do more stuff
return true;
}
public bool Test()
{
return RunTheMethod(Method1);
}
}
Passing a function as a function parameter
You can use Action
to do that
using System;
// ...
public void DoSomething(Action callback)
{
// do something
callback?.Invoke();
}
and either pass in a method call like
private void DoSomethingWhenDone()
{
// do something
}
// ...
DoSomething(DoSomethingWhenDone);
or using a lambda
DoSomething(() =>
{
// do seomthing when done
}
);
you can also add parameters e.g.
public void DoSomething(Action<int, string> callback)
{
// dosomething
callback?.Invoke(1, "example");
}
and again pass in a method like
private void OnDone(int intValue, string stringValue)
{
// do something with intVaue and stringValue
}
// ...
DoSomething(OnDone);
or a lambda
DoSomething((intValue, stringValue) =>
{
// do something with intVaue and stringValue
}
);
Alternatively also see Delegates
and especially for delegates with dynamic parameter count and types check out this post
C# - Passing functions (with arguments) as arguments of a function
I would like to suggest another approach for your code.
Maybe, you can keep a separated list with all the functions you need to verify, and run each method inside a very simple loop (foreach), in this case:
- the code will be very friendly (easy to understand)
- better maintainability
- you can review less code and add more functionality (for instance, you may inject some code and just add another Func<> into your List<>)
Please, take a look at the following example:
static class Program
{
private static void Main(string[] args)
{
var assertions = new List<Func<object[], bool>>
{
Assertion1,
Assertion2,
Assertion3
};
var yourResult = Assert(assertions, 1, "1", true);
Console.WriteLine(yourResult); // returns "True" in this case
Console.ReadLine();
}
private static bool Assert(IEnumerable<Func<object[], bool>> assertions, params object[] args)
{
// the same as
// return assertions.Aggregate(true, (current, assertion) => current & assertion(args));
var result = true;
foreach (var assertion in assertions)
result = result & assertion(args);
return result;
}
private static bool Assertion1(params object[] args)
{
return Convert.ToInt32(args[0]) == 1;
}
private static bool Assertion2(params object[] args)
{
return Convert.ToInt32(args[0]) == Convert.ToInt32(args[1]);
}
private static bool Assertion3(params object[] args)
{
return Convert.ToBoolean(args[2]);
}
}
C# How can I pass a function as a argument?
You are passing a function of type void (int)
which in C# is:
Action<int>
So, replace your ***Function myFunctionName***
with Action<int> myFunctionName
and you should be good. The Action
type takes from 0 to several generic parameters, corresponding to the types of the arguments.
If your function returned something other than void
, you would use the Func<...>
generic type. The last generic argument would be the return type.
Passing a function as parameter
Sure you can use the Func<T1, T2, TResult>
delegate:
public String myMethod(
Func<string, string, string> f1,
Func<string, string, string> f2)
{
//code
}
This delegate defines a function which takes two string parameters and return a string. It has numerous cousins to define functions which take different numbers of parameters. To call myMethod
with another method, you can simply pass in the name of the method, for example:
public String doSomething(String s1, String s2) { ... }
public String doSomethingElse(String s1, String s2) { ... }
public String myMethod(
Func<string, string, string> f1,
Func<string, string, string> f2)
{
//code
string result1 = f1("foo", "bar");
string result2 = f2("bar", "baz");
//code
}
...
myMethod(doSomething, doSomethingElse);
Of course, if the parameter and return types of f2
aren't exactly the same, you may need to adjust the method signature accordingly.
Passing Function as Parameter ( CS1503 )
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NewVSFunction
{
public static class MykytaHttpFunction
{
public static void Main(string[] args)
{
string Inputs = Console.ReadLine();
List<int> UnSorted = new List<int>();
for (int i = 0; i < Inputs.Split(' ').Count(); i++)
{
UnSorted.Add(int.Parse(Inputs.Split(' ')[i]));
}
CheckTimeOfSorting(SortWithTwoLoops); // <--- Error ( Can't convert from method group to Func<List<int>>)
Console.WriteLine(String.Join(" ", UnSorted));
}
public static void CheckTimeOfSorting(Func<List<int>, List<int>> SortingFunc)
{
}
public static List<int> SortWithTwoLoops(List<int> UnSorted)
{
List<int> Result = UnSorted;
for (int i = 0; i < Result.Count; i++)
{
for (int j = i + 1; j < Result.Count; j++)
{
if (Result[i] > Result[j])
{
int temp1 = Result[i];
int temp2 = Result[j];
Result[i] = temp2;
Result[j] = temp1;
}
}
}
return Result;
}
}
}
you need to specify an type to return in Func, see updated code
Passing in a function as a function parameter
In your case you want to pass a Func<double, double>
. Like so
double integrate(double b, double a, Func<double, double> f)
{
return (b-a) * (f(a) + f(b)) / 2;
}
double integrand = integrate(0, 2 * Math.PI, x => x*x + 2*x);
Passing a Function (with parameters) as a parameter?
It sounds like you want a Func<T>
:
T GetCachedValue<T>(string key, Func<T> method) {
T value;
if(!cache.TryGetValue(key, out value)) {
value = method();
cache[key] = value;
}
return value;
}
The caller can then wrap this in many ways; for simple functions:
int i = GetCachedValue("Foo", GetNextValue);
...
int GetNextValue() {...}
or where arguments are involved, a closure:
var bar = ...
int i = GetCachedValue("Foo", () => GetNextValue(bar));
C# pass function as argument
What you are trying to send into the method are not delegates.
You can use lambda expressions to create delegates for the method:
int time1 = Search(() => list.Contains(item));
int time2 = Search(() => dictionary.ContainsKey(anotheritem));
The ()
represents zero input parameters.
Related Topics
Reading from a Text File in C#
Modifying a JSON File Using System.Text.JSON
Run .Exe Executable File in Azure Function
Generics: Casting and Value Types, Why Is This Illegal
How to Delay Shutdown and Run a Process in Window Service
"Interface Not Implemented" When Returning Derived Type
Get Line Number for Xelement Here
C# Creating an Unknown Generic Type at Runtime
How to Get a Combination of Keys in C#
Executing Query with Parameters
Configureawait Pushes the Continuation to a Pool Thread
Changing Font for Richtextbox Without Losing Formatting
ASP.NET MVC Route to Catch All *.Aspx Requests
Discovering Derived Types Using Reflection