I usually check nullable types with if (foo is not null), and afterwards I can use foo like the non-null type. Why doesn't this work with structs? Even the ! operator does not help. Is this a bug or am I missing something? What's the shortest workaround?
Foo? foo = new Foo { a = "foo" };
if (foo is not null) {
Console.WriteLine(foo.a); // Works, prints "foo"
}
Bar? bar = new Bar { a = "bar" };
if (bar is not null) {
Console.WriteLine(bar.a); // Error: Bar? does not contain a definition for "a"
Console.WriteLine(bar!.a); // Same error
}
class Foo {
public string a;
}
struct Bar {
public string a;
}
Nullable<T>which is completely different from a nullable reference type. You have to use.Valueto access the value of a nullable struct.if (foo is Foo notNullFoo) Console.WriteLine(notNullFoo.a).{}can be used instead:if (bar is {} notNullBar) Console.WriteLine(notNullBar.a). EliminatingnotNullBarcan only be done at the cost of exposing the structural differences between nullable reference types and nullable value types.