It seems to me there is really no guarantee that a non-nullable variable won't ever have null. Imagine I have a class that has one property that is not nullable:
public class Foo
{
public Foo(string test)
{
Test = test;
}
public string Test {get;set;}
}
Now that might seem like it's now cannot be null. But if we reference this class with another library that does not use nullable context, nothing stops it from sending null in there.
Is that correct or there are some runtime checks as well perhaps that ensure this?
Even in your own code, if you choose to do so, you can pass
null
, using the null-forgiving operator.null!
is considered to be not-null so far as the compiler's nullability analysis is concerned.This is what MS says about (https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/upgrade-to-nullable-references#interfaces-with-external-code):
You are correct, other code which is not using the new feature could assign null to this property, there are no run-time checks it is just complier hints.
You could always do it yourself if you want a runtime check:
Note that you can guarantee not being null in most of your code, you just need to add guards to your top-level Public API and make sure classes are appropriately sealed etc.
Of course people can still use reflection to f*** your code up, but then its on them
someone can always do
May be you can use Domain Driven Design
To deal with null checks and also make your code readable, I suggest Null Object Design pattern.
More reading here:
https://www.c-sharpcorner.com/article/null-object-design-pattern/
Basically, it involves creating a new object which is derived from same interface and has null instance.
Example:
Nulls cant be avoided, however they can be checked cleanly.