C
C#3mo 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
Angius3mo ago
if (FilePath is not {} path)
{
return;
}
// `path` is not null
if (FilePath is not {} path)
{
return;
}
// `path` is not null
cheeze2000
cheeze20003mo ago
what is this called? and where can i learn about this
Angius
Angius3mo ago
Just a part of pattern matching
reflectronic
reflectronic3mo ago
this tells it that it is not null there is nothing more you need to do
maxmahem
maxmahem3mo 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
reflectronic3mo ago
whether the variable is declared as nullable is different from whether it is null right now
reflectronic
reflectronic3mo ago
are you on an updated version of the C# extension? it should tell you this
No description
cheeze2000
cheeze20003mo ago
this is mine
No description
cheeze2000
cheeze20003mo ago
No description
reflectronic
reflectronic3mo ago
well, yes... if it's not null, you return so, if you didn't return, it's null
cheeze2000
cheeze20003mo ago
wait... what am i doing
reflectronic
reflectronic3mo ago
if you change it to is null that the warning will go away
cheeze2000
cheeze20003mo ago
ok i have another one public Range? Location { get; init; }
cheeze2000
cheeze20003mo ago
No description
reflectronic
reflectronic3mo ago
yes, that's because Range is a struct
cheeze2000
cheeze20003mo ago
ohhh
reflectronic
reflectronic3mo 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
cheeze20003mo ago
thanks! can i use this pattern matching on the FilePath too? if (FilePath is not string path)
reflectronic
reflectronic3mo ago
yes
cheeze2000
cheeze20003mo ago
FilePath is string? ok nice