Why do we get possible dereference null reference warning, when null reference does not seem to be possible?

This is effectively a duplicate of the answer that @stuartd linked, so I’m not going to go into super deep details here. But the root of the matter is that this is neither a language bug nor a compiler bug, but it’s intended behavior exactly as implemented. We track the null state of a variable. … Read more

The annotation for nullable reference types should only be used in code within a ‘#nullable’ context

For anyone ending up here. You can put #nullable enable on top of the file for a file-by-file approach as suggested by @Marc in the comments. You can also use combinations of #nullable enable/disable to annotate just parts of the file class Program { static void Main(string[] args) { #nullable enable string? message = “Hello … Read more

How to enable Nullable Reference Types feature of C# 8.0 for the whole project

In Visual Studio 16.2 (from preview 1) the property name is changed to Nullable, which is simpler and aligns with the command line argument. Add the following properties to your .csproj file. <PropertyGroup> <Nullable>enable</Nullable> <LangVersion>8.0</LangVersion> </PropertyGroup> If you’re targeting netcoreapp3.0 or later, you don’t need to specify a LangVersion to enable nullable reference types. For … Read more

How to use .NET reflection to check for nullable reference type

In .NET 6, APIs were added to handle this, see this answer. Prior to this, you need to read the attributes yourself. This appears to work, at least on the types I’ve tested it with. public static bool IsNullable(PropertyInfo property) => IsNullableHelper(property.PropertyType, property.DeclaringType, property.CustomAttributes); public static bool IsNullable(FieldInfo field) => IsNullableHelper(field.FieldType, field.DeclaringType, field.CustomAttributes); public static … Read more

What does null! statement mean?

The key to understanding what null! means is understanding the ! operator. You may have used it before as the “not” operator. However, since C# 8.0 and its new “nullable-reference-types” feature, the operator got a second meaning. It can be used on a type to control Nullability, it is then called the “Null Forgiving Operator” … Read more