✅ Null check not enough to safely convert from nullable enum

I have a class declaring an enum and a nullable value for that enum:
public readonly StdModeTypes? smt;
public readonly StdModeTypes? smt;
I then try to reference that field from a second class:
if(cmodeCur.smt != null)
mapModesWithStdTypes[cmodeCur.smt] = cmodeCur;
if(cmodeCur.smt != null)
mapModesWithStdTypes[cmodeCur.smt] = cmodeCur;
Yet even with the null check, the IDE is insisting that smt could be null and won't let me use the value:
Error CS1503 Argument 1: cannot convert from 'BestChat.IRC.Data.Defs.ChanMode.StdModeTypes?' to 'BestChat.IRC.Data.Defs.ChanMode.StdModeTypes'
Error CS1503 Argument 1: cannot convert from 'BestChat.IRC.Data.Defs.ChanMode.StdModeTypes?' to 'BestChat.IRC.Data.Defs.ChanMode.StdModeTypes'
What's going on?
20 Replies
Will Pittenger
Will PittengerOP13mo ago
Given the smt field is readonly, isn't that enough to ensure the value hasn't changed?
mindhardt
mindhardt13mo ago
With value types the nullability is different With ref types it is just an annotation, more or less
Will Pittenger
Will PittengerOP13mo ago
OK.
mindhardt
mindhardt13mo ago
But with value types it is an actual type, in your case Nullable<StdModeTypes>
Will Pittenger
Will PittengerOP13mo ago
Too bad the compiler doesn't automatically unwrap it for you when the value can't be null.
mindhardt
mindhardt13mo ago
if(cmodeCur.smt.HasValue)
mapModesWithStdTypes[cmodeCur.smt.Value] = cmodeCur;
if(cmodeCur.smt.HasValue)
mapModesWithStdTypes[cmodeCur.smt.Value] = cmodeCur;
.HasValue is the same as != null or is not null In this case
if(cmodeCur.smt is { } smt)
mapModesWithStdType[smt] = cmodeCur;
if(cmodeCur.smt is { } smt)
mapModesWithStdType[smt] = cmodeCur;
This is also an option if you like patterns
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Yup
Yup13mo ago
I have the ultimate solution for this
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Yup
Yup13mo ago
PHP
MODiX
MODiX13mo ago
That command had an error
UnknownCommand: Unknown command.
Remove your reaction to delete this message
mindhardt
mindhardt13mo ago
$bam
MODiX
MODiX13mo ago
User bammed successfully.
Yup
Yup13mo ago
Unknown command $bam @Hin
MODiX
MODiX13mo ago
User bammed successfully.
Will Pittenger
Will PittengerOP13mo ago
Bam?
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
mindhardt
mindhardt13mo ago
Yup
Unknown User
Unknown User13mo ago
Message Not Public
Sign In & Join Server To View
Will Pittenger
Will PittengerOP13mo ago
Yes. Thanks. Used to classes.
Want results from more Discord servers?
Add your server