Can I declare a variable that is used in a line and discarded right after?

Viewed 38

Suppose I have this code:

int a = 1;
int b = 2;
string s = (a + b == 3 ? "3" : array[a + b]);

I would like to declare a "local" variable to store (a+b) so that I don't need to compute it twice. I imagine something like that:

int a = 1;
int b = 2;
string s = (c == 3 ? "3" : array[c]) where c = a + b;
//from now on, c doesn't exist anymore

I know where doesn't exist. I tried to use using var c = a + b but I don't think it's possible. Is there a way?

1 Answers

What you want to do reminds me of Kotlin's scope functions, specifically let. You can write an extension method for this:

static class ScopeFunctions
{
    public static U Let<T, U>(this T x, Func<T, U> func) => func(x);
}

Usage:

string s = (a + b).Let(x => 
    (x == 3 ? "3" : array[x])
);

x becomes the "'local' variable to store (a+b) so that I don't need to compute it twice" that you "discard right after", as x will be out of scope outside the lambda.

Related