Skip to content

Possibly improved code-gen for "typeswitch" #31515

@gafter

Description

@gafter

We occasionally use a "typeswitch-style" switch in Roslyn. For example

        public static bool FormattingHelpers.IsCloseParenInStatement(this SyntaxToken token)
        {
            var statement = token.Parent as StatementSyntax;
            if (statement == null)
            {
                return false;
            }

            switch (statement)
            {
                case IfStatementSyntax ifStatement:
                    return ifStatement.CloseParenToken.Equals(token);
                case SwitchStatementSyntax switchStatement:
                    return switchStatement.CloseParenToken.Equals(token);
                case WhileStatementSyntax whileStatement:
                    return whileStatement.CloseParenToken.Equals(token);
                case DoStatementSyntax doStatement:
                    return doStatement.CloseParenToken.Equals(token);
                case ForStatementSyntax forStatement:
                    return forStatement.CloseParenToken.Equals(token);
                case CommonForEachStatementSyntax foreachStatement:
                    return foreachStatement.CloseParenToken.Equals(token);
                case LockStatementSyntax lockStatement:
                    return lockStatement.CloseParenToken.Equals(token);
                case UsingStatementSyntax usingStatement:
                    return usingStatement.CloseParenToken.Equals(token);
                case FixedStatementSyntax fixedStatement:
                    return fixedStatement.CloseParenToken.Equals(token);
            }

            return false;
        }

The generated code might possibly be improved by calling GetType() on the input and including a sequence of tests against the type desired (when consecutive tests are for sealed types).

We would have to measure whether we actually get any improvement before committing to such an optimization.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions