elite5472 elite5472 - 1 month ago 5
C# Question

Are there any official ways to write an Immediately Invoked Function Expression?

Something like this:

var myObject = new MyClass()
{
x = " ".Select(y =>
{
//Do stuff..
if (2 + 2 == 5)
return "I like cookies";
else if (2 + 2 == 3)
return "I like muffins";
//More conditions...
else
return "I'm a bitter old man";
})
};


I realize Select is not intended to be used this way. But yeah, what are some other ways to do the same thing?

Answer

I'm surprised no one's mentioned this yet, but you could use the Lazy<T> class:

var myObject = new MyClass()
{
    x = new Lazy<string>(() =>
    {
        //Do stuff..
        if (2 + 2 == 5)
            return "I like cookies";
        else if (2 + 2 == 3)
            return "I like muffins";
        //More conditions...
        else
            return "I'm a bitter old man";
    }).Value // <-- Evaluate the function here
};

Alternatively, if you want to avoid having to specify the return type anywhere (as you do with new Lazy<string> because constructors do not support type inference), you can implement a simple generic method like this:

public static T Eval<T>(Func<T> func)
{
    return func();
}

And then you can call like this:

var myObject = new MyClass()
{
    x = Eval(() =>
    {
        //Do stuff..
        if (2 + 2 == 5)
            return "I like cookies";
        else if (2 + 2 == 3)
            return "I like muffins";
        //More conditions...
        else
            return "I'm a bitter old man";
    })
};