-
Not sure if this is intentional, but this kind of struck me as an oddity when working with property patterns. public class Foo
{
public string Value {get;}
public Foo(string value) => Value = value;
}
...
if (foo.Value is { Length: > 5} v) v in this context cannot be null, but v is declared as a if(foo.Value is string { Length: > 5} v) I find this odd behavior, as using property patterns or even leaving it blank |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It's intentional. var v = foo.Value;
Console.WriteLine(v.Length); // No warning even though v is `string?` because it's tracked as not null
v = fooThatMightBeNull; // No warning here because v is `string?` not `string`
Console.WriteLine(v.Length); // Warning because it's tracked as maybe-null Initially // This assignment only works because `current` is declared as nullable.
// ↓
for (var current = someNonNullType; current is not null; current = current.BaseType)
{
// Do something with each type.
} However, the IDE sure feels to me like it goes out of its way to confuse you here by not mentioning the 'not null' initial tracking when you hover over the declaration, which is exactly where my muscle memory takes me most of the time. This could be improved. The tracked state can be seen anywhere else though: |
Beta Was this translation helpful? Give feedback.
It's intentional.
v
is declared as capable of holdingstring?
, but the fact that the value it holds is not null is still tracked just the same up to the point where you assign something nullable to it. It's the same if you do this:Initially
var
did not work this way, but it became clear that this would be too painful for such a common scenario in the wild. If it wasn't for this design, then this (and non-loop vers…