4
votes

I have a C# project with nullable reference types enabled:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <!-- more stuff here -->
</Project>

I've set a couple of warnings to become errors in my .editorconfig:

[*.cs]

# CS8600: Converting null literal or possible null value to non-nullable type.
dotnet_diagnostic.CS8600.severity = error

# CS8603: Possible null reference return.
dotnet_diagnostic.CS8603.severity = error

In my project, I have a class, and the following won't compile, which is perfect:

public class NullableCompilerChecking
{
   public string WontCompile(string? input)
    => input;  // error: "possible null reference return"
}

Now for the problem. My project references another project called "Library". Library is null-oblivious. In Library, I have the following:

  public static class Strings
  {
    public static string Null => null;
  }

The problem is that when I reference the Strings class from my library, I lose the wonderful null-checking. For example, the following compiles and throws at runtime:

    [Test]
    public void SomeTest()
    {
      var myString = Strings.Null;
      var myIndex = myString.IndexOf("a");
    }

What I would have wanted is for Library's string to by default come to the null-aware code as a string? rather than a string. Can I do that?

1
im really failing to understand the question lol. Anyways - you do realize that string is a nullable type (since its a reference type, and they are by definition nullable) so a string can be null and so the compiler does not throw warnings or errors for a null assignment to string. The same way writing string s = null would still compile because its valid so there's really now way for the compiler to detect that. Thats why nullable types are marked with the ? symbol so the compiler knows it can or cant be nullable - sommmen

1 Answers

2
votes

As far as I am aware, if you want new null checking on a library that does not support it, you have to create a wrapper around it, with proper null awareness. For example:

public static class Strings
{
  public static string Null => null;
}

// In your code you will use only the wrapper
public static class StringsWrapper
{
  public static string? Null => Strings.Null;
}

In case you are using ReSharper, another lazy option would be to turn on pessimistic nullability analisys, which gives you a warning/error, everywhere where you are using value that might be null.