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 confused me.
As I understand it, when you do not add the ?
symbol to a type, it is treated as a non-nullable reference type. However, in the Main
method of my code, the compiler does not complain when I check if myClass
is null
. Shouldn't the compiler know by this point that myClass
is non-nullable?
Update:
To help clarify this, I have added a stub method to the MyClass
class. As you can see, at this point the compiler is aware that myClass
is not null
. But why does it allow the next null
check? It does not make sense to me."
#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()
{
}
}
}