C
C#7mo ago
cheeze2000

assure compiler type is not null

i have a code that early returns if a property is null. how do i tell the compiler the property is not null afterwards?
No description
20 Replies
Angius
Angius7mo ago
if (FilePath is not {} path)
{
return;
}
// `path` is not null
if (FilePath is not {} path)
{
return;
}
// `path` is not null
cheeze2000
cheeze2000OP7mo ago
what is this called? and where can i learn about this
Angius
Angius7mo ago
Just a part of pattern matching
reflectronic
reflectronic7mo ago
this tells it that it is not null there is nothing more you need to do
maxmahem
maxmahem7mo ago
variables declared as var's always shows up as nullable in inspection. That doesn't mean the compiler sees it as nullable, if that makes sense?
reflectronic
reflectronic7mo ago
whether the variable is declared as nullable is different from whether it is null right now
reflectronic
reflectronic7mo ago
are you on an updated version of the C# extension? it should tell you this
No description
cheeze2000
cheeze2000OP7mo ago
this is mine
No description
cheeze2000
cheeze2000OP7mo ago
No description
reflectronic
reflectronic7mo ago
well, yes... if it's not null, you return so, if you didn't return, it's null
cheeze2000
cheeze2000OP7mo ago
wait... what am i doing
reflectronic
reflectronic7mo ago
if you change it to is null that the warning will go away
cheeze2000
cheeze2000OP7mo ago
ok i have another one public Range? Location { get; init; }
cheeze2000
cheeze2000OP7mo ago
No description
reflectronic
reflectronic7mo ago
yes, that's because Range is a struct
cheeze2000
cheeze2000OP7mo ago
ohhh
reflectronic
reflectronic7mo ago
(probably) it means that Range? is a Nullable<Range> which means, you need to unrap the value manually you can do it using range.HasValue, with range.Value or range.GetValueOrDefault() you can also use the pattern matching if (Location is not Range r) or if (Location is not { } r)
cheeze2000
cheeze2000OP7mo ago
thanks! can i use this pattern matching on the FilePath too? if (FilePath is not string path)
reflectronic
reflectronic7mo ago
yes
cheeze2000
cheeze2000OP7mo ago
FilePath is string? ok nice
Want results from more Discord servers?
Add your server