예제 #1
0
        public static bool TryConvertToArrowExpressionBody(
            this BlockSyntax block,
            SyntaxKind declarationKind,
            LanguageVersion languageVersion,
            ExpressionBodyPreference preference,
            [NotNullWhen(true)] out ArrowExpressionClauseSyntax?arrowExpression,
            out SyntaxToken semicolonToken)
        {
            // We can always use arrow-expression bodies in C# 7 or above.
            // We can also use them in C# 6, but only a select set of member kinds.
            var acceptableVersion =
                languageVersion >= LanguageVersion.CSharp7 ||
                (languageVersion >= LanguageVersion.CSharp6 && IsSupportedInCSharp6(declarationKind));

            if (acceptableVersion &&
                block.TryConvertToExpressionBody(languageVersion, preference, out var expression, out semicolonToken))
            {
                arrowExpression = SyntaxFactory.ArrowExpressionClause(expression);

                var parent = block.GetRequiredParent();

                if (parent.Kind() == SyntaxKind.GetAccessorDeclaration)
                {
                    var comments = parent.GetLeadingTrivia().Where(t => !t.IsWhitespaceOrEndOfLine());
                    if (!comments.IsEmpty())
                    {
                        arrowExpression = arrowExpression.WithLeadingTrivia(
                            parent.GetLeadingTrivia());
                    }
                }

                return(true);
            }

            arrowExpression = null;
            semicolonToken  = default;
            return(false);
        }