C
C#16mo 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
Aaron16mo ago
you can't you can never have a boxed nullable
Hugh
Hugh16mo ago
ahh shit... okay
Pobiega
Pobiega16mo ago
int val = 123;
object? nullable = new int?(val);
int val = 123;
object? nullable = new int?(val);
?
Hugh
Hugh16mo ago
I don't know that it's int at that point
Aaron
Aaron16mo ago
that just gets boxed as an int
Hugh
Hugh16mo ago
I can re-work some other code further up the chain to make this work
Aaron
Aaron16mo ago
if the Nullable has no value, when you box it, it gives you a literal null
Pobiega
Pobiega16mo ago
I'm not sure what the goal here is
MODiX
MODiX16mo 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
Hugh16mo ago
If this isn't possible, then I've got another approach that I can try here Thanks both