diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1011,7 +1011,12 @@ Style.Language == FormatStyle::LK_JavaScript) break; if (Style.isCSharp()) { - if (Line.MustBeDeclaration && !Contexts.back().IsExpression) { + // `Type? name;` and `Type? name =` can only be nullable types. + // Line.MustBeDeclaration will be true for `Type? name;`. + if (!Contexts.back().IsExpression && + (Line.MustBeDeclaration || + (Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next && + Tok->Next->Next->is(tok::equal)))) { Tok->Type = TT_CSharpNullable; break; } diff --git a/clang/unittests/Format/FormatTestCSharp.cpp b/clang/unittests/Format/FormatTestCSharp.cpp --- a/clang/unittests/Format/FormatTestCSharp.cpp +++ b/clang/unittests/Format/FormatTestCSharp.cpp @@ -631,7 +631,17 @@ FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp); Style.SpacesInSquareBrackets = false; + verifyFormat(R"(// +public class A { + void foo() { int? value = some.bar(); } +})", + Style); // int? is nullable not a conditional expression. + + verifyFormat(R"(void foo(int? x, int? y, int? z) {})", + Style); // Nullables in function definitions. + verifyFormat(R"(public float? Value;)", Style); // no space before `?`. + verifyFormat(R"(int?[] arr = new int?[10];)", Style); // An array of a nullable type. }