Within C# is it possible to create a new function on the fly to define a variable?
I know that
string getResult() {
    if (a)
        return "a";
    return "b";
}
String result = getResult();
is possible, but I'm looking for something like
String result = new string getResult() {
    if (a)
        return "a";
    return "b";
}
Is this possible? If so, would someone demonstrate?
EDIT It is possible
Edit: Final - Solution
This is the end result of what I barbarically hacked together
Func<string> getResult = () =>
{
    switch (SC.Status)
    {
        case ServiceControllerStatus.Running:
            return "Running";
        case ServiceControllerStatus.Stopped:
            return "Stopped";
        case ServiceControllerStatus.Paused:
            return "Paused";
        case ServiceControllerStatus.StopPending:
            return "Stopping";
        case ServiceControllerStatus.StartPending:
            return "Starting";
        default:
            return "Status Changing";
    }
};
TrayIcon.Text = "Service Status - " + getResult();
                One way to define such a function:
Func<bool, string> getResult = ( a ) => {
    if (a)
        return "a";
    return "b";
}
You can then invoke: string foo = getResult( true );. As a delegate, it can be stored/passed and invoked when needed.
Example:
string Foo( Func<bool, string> resultGetter ){
    return resultGetter( false );
}
You can also close around variables within scope:
bool a = true;
Func<string> getResult = () => {
    if (a)
        return "a";
    return "b";
}
string result = getResult();
                        You want to use the inline if statement.
string result = a ? "a" : "b";
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With