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