I am trying to use Nullable Reference Types in C# 8.0. I have set up a sample code to test it but something has baffled me!
As far as I understood, when we do not add ?
to the Type
it is treated as non-nullable. Then why in the Main() method the compiler does not complain that I am checking myClass
against null
? Shouldn't it be obvious by this point to the compiler that myClass
is non-nullable?
Update:
I added a stub method to MyClass. As you see, at this point the compiler is aware that myClass is not null. Why would it allow for the next null checking? It does not make sense!
#nullable enable
using System;
namespace ConsoleApp4
{
class Program
{
static void Main()
{
var service = new Service();
MyClass myClass = service.GetMyClass();
myClass.Write();
// I am curious why this line compiles!
if (myClass == null)
{
throw new ArgumentNullException();
}
}
}
public sealed class Service
{
private MyClass? _obj;
public MyClass GetMyClass()
{
if (_obj == null)
{
_obj = new MyClass();
}
return _obj;
}
}
public sealed class MyClass
{
public void Write()
{
}
}
}
MyClass
is aclass
and therefore a reference type. Whether it is declared with the?
operator or not, it's still nullable. - Barry O'Kanenull
value, but I'm struggling to find in the spec where it says one can't compare with anull
value. - David