The following code works properly in .NET core 3.1, but generates wrongly the warning CS8625 Cannot convert null literal to non-nullable reference type :
#nullable enable
using System.Threading;
namespace InterlockedExchangeNullProblem {
public class Class1 {
public Class1() {
object? o = new object();
var o1 = Interlocked.Exchange(ref o, null); // ok
class2? c = new class2();
var c1 = Interlocked.Exchange(ref c, null); // error CS8625 Cannot convert null literal to non-nullable reference type.
}
}
public class class2{}
}
If it works for object?
, it should also work for class2?
.
Solution:
var c2 = Interlocked.Exchange<class2?>(ref c, null);
Note: The compiler made c1 of type class2
instead class2?
.
If you agree that this needs to be corrected, then please upvote:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.