Bob5421
Bob5421

Reputation: 9073

Can we say a C# class is automatically nullable?

Look at this C# code (.Net6 Console project):

class MyClass {
  public int a;
  public int b;
}

Now, look at this declaration:

MyClass obj = null;

At this step, I have no error and no warnings. So I suppose MyClass is a nullable type ? Am I Wrong at this step ?

Now look at this code:

var sr = new StringReader(xmlString);
var deser = new XmlSerializer(typeof(MyClass));
MyClass obj2 = (MyClass) deser.Deserialize(sr);

It works but I have a CS8600 warning.

If I want to remove this warning I have to write this:

MyClass? obj2 = (MyClass?) deser.Deserialize(sr);

So MyClass is nullable or not nullable ?

Thanks a lot

Upvotes: 0

Views: 217

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

You can always assign null to a reference type; however, whether you get a warning depends on whether you are in a Nullable context and whether you typed it as nullable (?).

A nullable reference type is the same type as the non nullable one. I.e.:

string? nullable = "hello";
string nonNullable = "world";

if (nullable.GetType() == nonNullable.GetType()) {
    // Does always execute this
    Console.WriteLine("same type");
}

if (nullable.GetType() == typeof(string)) {
    // Does always execute this
    Console.WriteLine("same type");
}

// typeof(string?) generates
// Error CS8639 The typeof operator cannot be used on a nullable reference type.

The nullability is only a hint for the compiler to allow it analyzing the control flow and to detect possible null references enabling it to issue corresponding warnings.

Starting with .NET 6 the nullable context is enabled by default but you can still disable it, e.g., with <Nullable>disable</Nullable> in the project file. In previous .NET versions you had to enable it with <Nullable>enable</Nullable>.

You can also enable or disable the nullable context for specific code regions with the #nullable directive.

Upvotes: 3

Related Questions