Use Case:
I want to eliminate the business of having to null-check every object reference my library functions will have to deal with.
Let's say I create MyLibrary.csproj
like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<WarningsAsErrors>Nullable</WarningsAsErrors>
</PropertyGroup>
</Project>
And let's say a client project ( MyClient.csproj
) references MyLibrary:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="{...}\MyLibrary\MyLibrary.csproj" />
</ItemGroup>
</Project>
Notice that the client project has disabled the Nullable reference types feature. (I could have also left it enabled, but still omitted the <WarningsAsErrors>Nullable</WarningsAsErrors>
element.)
And now let's say that client code does something stupid, like this:
...
MyLibrary.DoSomething( getValueThatMayBeNull() );
...
I am used to protecting against this situation by writing my library code with a formulation something like this:
namespace MyBrand;
public class MyLibrary
{
public MyLibrary { ... }
public void DoSomething( string myData )
{
if( myData == null )
throw new ArgumentNullException();
else
doWork( myData );
}
}
However, I want to know if activating the Nullable reference types feature in my library code - and specifying that I want a compile-time error for potentially null references, rather than just a warning - means that it is now safe to write my library code like this:
...
public void DoSomething( string myData )
{
doWork( myData );
}
...
Will the client code fail to compile because the library expects no null references? Or will it succeed, because the client code has opted out of null references as errors? (Meaning that I still need to write my library code with null checks, regardless of whether the null reference feature is enabled or not.)
Many thanks!