✅ 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 PittengerOP15mo ago
Given the smt field is readonly, isn't that enough to ensure the value hasn't changed?
mindhardt
mindhardt15mo ago
With value types the nullability is different With ref types it is just an annotation, more or less
Will Pittenger
Will PittengerOP15mo ago
OK.
mindhardt
mindhardt15mo ago
But with value types it is an actual type, in your case Nullable<StdModeTypes>
Will Pittenger
Will PittengerOP15mo ago
Too bad the compiler doesn't automatically unwrap it for you when the value can't be null.
mindhardt
mindhardt15mo 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 User15mo ago
Message Not Public
Sign In & Join Server To View
Yup
Yup15mo ago
I have the ultimate solution for this
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
Yup
Yup15mo ago
PHP
MODiX
MODiX15mo ago
That command had an error
UnknownCommand: Unknown command.
Remove your reaction to delete this message
mindhardt
mindhardt15mo ago
$bam
MODiX
MODiX15mo ago
User bammed successfully.
Yup
Yup15mo ago
Unknown command $bam @Hin
MODiX
MODiX15mo ago
User bammed successfully.
Will Pittenger
Will PittengerOP15mo ago
Bam?
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
mindhardt
mindhardt15mo ago
Yup
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
Will Pittenger
Will PittengerOP15mo ago
Yes. Thanks. Used to classes.

Did you find this page helpful?