Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Variable = new function () {};

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();
like image 354
Slushba132 Avatar asked Aug 26 '12 01:08

Slushba132


2 Answers

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();
like image 130
Tim M. Avatar answered Oct 05 '22 02:10

Tim M.


You want to use the inline if statement.

string result = a ? "a" : "b";
like image 39
Daniel A. White Avatar answered Oct 05 '22 03:10

Daniel A. White