Search code examples
c#javascriptanonymous-methodsanonymous-function

JavaScript-like anonymous functions in C#


Can the following be done in C#?:

var greeting = "Hello" + function ()
{
    return " World";
}() + "!";

I want to do something along the lines of this (C# pseudo code):

var cell = new TableCell { CssClass = "", Text = return delegate ()
{
     return "logic goes here";
}};

Basically I want to implement in-line scoping of some logic, instead of moving that chunk logic into a separate method.


Solution

  • If you're using an anonymous type then you'll have to cast the anonymous method or lambda expression explicitly; if you're assigning to a property where the type is already known, you won't. For example:

    var cell = new TableCell { CssClass = "", Text = (Func<string>) (() =>
    {
         return "logic goes here";
    })};
    

    It's slightly uglier, but it works.

    But yes, you can certainly use an anonymous function like this. You'll need to explicitly call it when you want to retrieve the text, mind you:

    Console.WriteLine("{0}: {1}", cell.CssClass, cell.Text());