In a C# 8 project, I am using nullable reference types and am getting an unexpected (or at least, unexpected to me) CS8629 warning,
bool singleContent = x.DataInt != null;
bool multiContent = x.DataNvarchar != null;
if (singleContent && multiContent)
{
throw new ArgumentException("Expected data to either associate a single content node or " +
"multiple content nodes, but both are associated.");
}
if (singleContent)
{
var copy = x.DataInt.Value; // CS8629 here
newPropertyData.DataNvarchar = $"umb://{type.UdiType}/{Nodes[copy].UniqueId.ToString("N")}";
}
I've decided to use GetValueOrDefault()
as a workaround, but I'd like to know how to prove to the compiler that x.DataInt
can't be null if singleContent
is checked.
Note that the type of x.DataInt
is int?
.
Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type.
Although using nullable reference types can introduce its own set of problems, I still think it's beneficial because it helps you find potential bugs and allows you to better express your intent in the code. For new projects, I would recommend you enable the feature and do your best to write code without warnings.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
This is just a temporary answer until Julien Couvreur, one of the designers of nullable reference types posts the definitive answer (nagging). I'm posting this here because the question will be asked again once C# 8 is released.
As Julien answers in 3 Github issues #34800 , #37032 and #36149 this is a known limitation of the C# 8 analyzer that's out of scope for C# 8.
This requires alias analysis which (just guessing here) means that the analyzer will be able to analyze aliased expressions, ie expressions whose results are "hidden" behind temporary variables (possibly parameters too?).
Perhaps we can ask him or Mads Torgersen online when .NET Core 3 is released during .NET Conf 2019 about a release date (totally not nagging)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With