Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Variable declaration can be inlined" even when used by multiple cases in a switch #24070

Closed
zspitz opened this issue May 6, 2021 · 1 comment

Comments

@zspitz
Copy link
Contributor

zspitz commented May 6, 2021

I have code like the following:

Dictionary<string, (int start, int length)> pathSpans;
var ret = x.o switch {
    Expression expr => expr.ToString(TextualTree, out pathSpans, "C#"),
    MemberBinding mbind => mbind.ToString(TextualTree, out pathSpans, "C#"),
    ElementInit init => init.ToString(TextualTree, out pathSpans, "C#"),
    SwitchCase switchCase => switchCase.ToString(TextualTree, out pathSpans, "C#"),
    CatchBlock catchBlock => catchBlock.ToString(TextualTree, out pathSpans, "C#"),
    LabelTarget labelTarget => labelTarget.ToString(TextualTree, out pathSpans, "C#"),
    _ => throw new InvalidOperationException(),
};

The analyzer recommends inlining the variable in the first case of the switch:

var ret = x.o switch {
    Expression expr => expr.ToString(TextualTree, out var pathSpans, "C#"),
...

but if I do that, the variable isn't available to the other cases in the switch.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

@BillWagner
Copy link
Member

Thanks for writing this @zspitz

If you accept that recommendation, you'd need to add the var declaration in the other switch arms as well:

Dictionary<string, (int start, int length)> pathSpans;
var ret = x.o switch {
    Expression expr => expr.ToString(TextualTree, out var pathSpans, "C#"),
    MemberBinding mbind => mbind.ToString(TextualTree, out var pathSpans, "C#"),
    ElementInit init => init.ToString(TextualTree, out var pathSpans, "C#"),
    SwitchCase switchCase => switchCase.ToString(TextualTree, out var pathSpans, "C#"),
    CatchBlock catchBlock => catchBlock.ToString(TextualTree, out var pathSpans, "C#"),
    LabelTarget labelTarget => labelTarget.ToString(TextualTree, out var pathSpans, "C#"),
    _ => throw new InvalidOperationException(),
};

I'll close this as an answered question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants