diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs index e4de84518d4ec..3e587de5d7458 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs @@ -161655,5 +161655,94 @@ public static void M1(Func f) { } // c1. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(15, 20)); } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51191")] + public void InterlockedExchange_WithNullCheckAndNullArgument() + { + var source = """ + #nullable enable + + using System.Threading; + + public class C { + private C? _obj; + + public void Rent() + { + if (_obj is not null) + { + C? o = Interlocked.Exchange(ref _obj, null); + if (o is not null) + { + Use(o); + } + } + } + + private void Use(C o) {} + } + """; + CreateCompilation(source).VerifyDiagnostics(); + } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51191")] + public void InterlockedCompareExchange_WithNullCheckAndNullArgument() + { + var source = """ + #nullable enable + + using System.Threading; + + public class C { + private C? _obj; + + public void Rent() + { + C? current = _obj; + if (current is not null) + { + C? o = Interlocked.CompareExchange(ref _obj, null, current); + if (o is not null) + { + Use(o); + } + } + } + + private void Use(C o) {} + } + """; + CreateCompilation(source).VerifyDiagnostics(); + } + + [Fact, WorkItem("https://github.com/dotnet/roslyn/issues/51191")] + public void InterlockedExchange_WithExplicitTypeArgument() + { + var source = """ + #nullable enable + + using System.Threading; + + public class C { + private C? _obj; + + public void Rent() + { + if (_obj is not null) + { + // Explicitly specifying the type argument should also work + C? o = Interlocked.Exchange(ref _obj, null); + if (o is not null) + { + Use(o); + } + } + } + + private void Use(C o) {} + } + """; + CreateCompilation(source).VerifyDiagnostics(); + } } }