C
C#2y ago
Hugh

✅ Converting value to nullable

I've got a point in my code where I've got:
int intValue = 5;
object? value = intValue; // contains a non-nullable value, an int, float, etc
Type type = typeof(int?);

value = ChangeType(value, type);
int intValue = 5;
object? value = intValue; // contains a non-nullable value, an int, float, etc
Type type = typeof(int?);

value = ChangeType(value, type);
I need to write ChangeType, and only have access to value and type. Using Convert.ChangeType() doesn't work here, and throws an exception. How can I convert this value to nullable successfully? Thanks
10 Replies
Aaron
Aaron2y ago
you can't you can never have a boxed nullable
Hugh
HughOP2y ago
ahh shit... okay
Pobiega
Pobiega2y ago
int val = 123;
object? nullable = new int?(val);
int val = 123;
object? nullable = new int?(val);
?
Hugh
HughOP2y ago
I don't know that it's int at that point
Aaron
Aaron2y ago
that just gets boxed as an int
Hugh
HughOP2y ago
I can re-work some other code further up the chain to make this work
Aaron
Aaron2y ago
if the Nullable has no value, when you box it, it gives you a literal null
Pobiega
Pobiega2y ago
I'm not sure what the goal here is
MODiX
MODiX2y ago
Windows10CE#8553
REPL Result: Success
int? i = null;
object? o = i;
object.ReferenceEquals(o, null)
int? i = null;
object? o = i;
object.ReferenceEquals(o, null)
Result: bool
True
True
Compile: 493.959ms | Execution: 36.655ms | React with ❌ to remove this embed.
Hugh
HughOP2y ago
If this isn't possible, then I've got another approach that I can try here Thanks both
Want results from more Discord servers?
Add your server