0

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.

cllpse
  • 21,396
  • 37
  • 131
  • 170

3 Answers3

10
var greeting = "Hello" + new Func<String>(() => " World")() + "!";
cllpse
  • 21,396
  • 37
  • 131
  • 170
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
2

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());
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Gonna put in a more verbose answer myself:

var tr = new TableRow { CssClass = "" };

tr.Cells.AddRange(new []
{
    new TableCell { CssClass = "", Text = "Hello" },
    new TableCell { CssClass = "", Text = new Func<String>(() => 
    {
        // logic goes here
        return "";
    })()}
});
cllpse
  • 21,396
  • 37
  • 131
  • 170