You can do anonymous functions in C# like you can in JavaScript:
JavaScript:
var s = (function ()
{
return "Hello World!";
}());
C#:
var s = new Func<String>(() =>
{
return "Hello World!";
})();
… In JavaScript you can pass functions to be executed by other functions. On top of that; you can pass parameters to the function which gets executed:
var f = function (message) // function to be executed
{
alert(message);
};
function execute(f) // function executing another function
{
f("Hello World!"); // executing f; passing parameter ("message")
}
Is the above example possible in C#?
Update
Use-case: I am iterating over a bunch of database, logging specific entities. Instead of calling my second function (F()) inside Log() of Logger, I’d like to call F() outside the class.
… Something along the lines of:
public void F(String databaseName)
{
}
public class Logger
{
public void Log(Function f)
{
var databaseName = "";
f(databaseName);
}
}
Absolutely – you just need to give the method an appropriate signature:
Note that you do have to specify the particular delegate type in the parameter – you can’t just declare it as
Delegatefor example.EDIT: Your database example is exactly the same as this – you want to pass in a string and not get any output, which is exactly what
Action<string>does. Except if you’re trying to call an existing method (F()in your code) you don’t even need a lambda expression – you can use method group conversions instead: