C#C
C#3y 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);


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
Was this page helpful?