Reputation: 91
I've looked but can't figure out why I am not getting an exception when I pass a null for a string parameter in a constructor when I have null reference types enabled.
Don't constructor parameters get treated as non-nullable?
Here's my constructor:
public ApiClient( string baseUrl, string authorizationToken ) {
string testString = null;
_apiClientBaseUrl = baseUrl ?? throw new ArgumentNullException( $"{nameof(baseUrl)} cannot be null" );
_authorizationToken = authorizationToken ?? throw new ArgumentNullException( $"{nameof(authorizationToken)} cannot be null" );
}
I do get an error for the string testString = null;
line.
If I remove the coded null tests I can pass in nulls for the 2 properties and don't get any error. The object will instantiate just fine.
I am in a .NET Core 3.1 project with this in the .csproj file:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Nullable>enable</Nullable>
<WarningsAsErrors>CS8600;CS8602;CS8603;CS8625</WarningsAsErrors>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
Upvotes: 3
Views: 367
Reputation: 143373
Nullable reference types are used for compile time static analysis only, as the docs state:
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. The compiler doesn't add any runtime checking for non-nullable reference types. The benefits are in the compile-time analysis. The compiler generates warnings that help you find and fix potential null errors in your code. You declare your intent, and the compiler warns you when your code violates that intent.
Upvotes: 7