DisallowNull for method parameters

Viewed 1210

I've recently stumbled upon the System.Diagnostics.CodeAnalysis namespace and the DisallowNull attribute. If I understand it correctly you should be able to decorate a parameter with it and Visual Studio should show a warning or error if you try to pass null to said parameter.

I.e.

void Test([DisallowNull] string str) { }

Test(null); //should generate some sort of alarm or shriek

But I don't see it happening in my project. What am I missing?

1 Answers

I. Ensure that nullable contex is enabled and langversion is 8.0 or greater in your csproj:

<PropertyGroup>
  <TargetFramework>netstandard2.1</TargetFramework>
  <Nullable>enable</Nullable>
  <LangVersion>8.0</LangVersion>
</PropertyGroup>

II.Check code:

enter image description here

III. [DisallowNull] is not needed for concrete types. [DisallowNull] with string will have the same warning as just string. You can use more simple string type.

IV. Use [AllowNull] and [DisallowNull] for unconstrained generic types (c#8)

V. You can use T? as alternative for [AllowNull] T for for unconstrained generic types (from c#9) see: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/unconstrained-type-parameter-annotations

Related