简体   繁体   中英

Possible to enforce nullable reference types?

If a class library was written with nullable reference types enabled, the developer may not always check for null , as the compiler will not give warnings/errors.

Take the following code in a library with nullable reference types enabled:

public class Class1
{
    public void MyMethod(string s)
    {
        // don't check for null as compiler is happy
        s.ToLower();
    }
    public void MyMethod2(string? s)
    {
        // check for null as compiler is warning otherwise
        if (s != null)
        {
            this.MyMethod(s);
        }
    }
}

If a consumer called Class1.MyMethod without enabling nullable reference types, they would not get a warning when making the following call:

var c = new Class1();
c.MyMethod(null);

Is it possible to somehow force—or at least warn—consuming code to enable nullable reference types?

It is not possible for good reason. If it could imagine you add a new library to your project and it forces you to update hundreds of thousands of lines of code.

As the nullability has no runtime effect, you as a library author should always test your arguments in public interface to validate invalid inputs. The library internals can safely rely on nullability if you validate inputs on public interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM