views:

165

answers:

4

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.

+8  A: 
var greeting = "Hello" + new Func<String>(() => " World")() + "!";
280Z28
Updated my question.
roosteronacid
Heh, very nice!
Nathan Ridley
Your answer helped me, but it doesn't match the question as good as Jon Skeet's answer.
roosteronacid
+1  A: 

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
A: 

As C# is a statically typed language, you'll probably want to declare the type of the TableCell class. In which case you need to know what type to make the Text property.

class TableCell
{
    public Func<string> Text { get; set; }

    // ... etc
}

So you can do this:

TableCell t = new TableCell 
              { 
                  Text = () => DateTime.Now.ToString();
              };

And then this:

Console.WriteLine(t.Text());
Daniel Earwicker
+1  A: 

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 "";
    })()}
});
roosteronacid