I need to take a nullable int and cast it as a nullable short. How can I get around the narrowing convention?
Asked
Active
Viewed 360 times
0
-
3By "narrowing convention" I assume you mean "narrowing conversion"... and by that I assume you mean how to stop an exception being thrown if the int is too big to fit into the short? Can you clarify? - Also, greetings from a fellow - years ago - VBForums.com member. Your alias and display picture instantly bought back many memories. – Simon Whitehead Feb 25 '14 at 21:41
-
Possible duplicate of http://stackoverflow.com/questions/10065452/c-sharp-casting-to-nullable-type – JonPall Feb 25 '14 at 21:45
-
Yes, my bad, narrowing conversion. Being sick and working doesnt turn out well lol. Si the geek is it? – RobDog888 Feb 25 '14 at 22:10
-
A simple cast will do the trick but do you really want to just corrupt data that doesn't fit in a short? – Chris Anderson Feb 25 '14 at 22:13
1 Answers
2
int? dsd = 1;
short? dsddd = (short?) dsd;
It seems to work pretty well :)?

Softwarehuset
- 815
- 4
- 10
-
A bit too quick. copy pasted the wrong code :) it still works both with null and a int value – Softwarehuset Feb 25 '14 at 21:44
-
I tried this before and it didnt work. I did it again and it worked but when I retesteed it it errored again. I think there is something else going on behind the scenes as this is of course a simplified version of my actual problem. – RobDog888 Feb 25 '14 at 22:11
-
Under all circumstances this is your answer :) You can Cast it :) You must find the force luke :) – Softwarehuset Feb 25 '14 at 22:13
-
I think I got it. Turns out the code to load the setting from the querystring upon page load was casting it as short? and the other code to load the setting from the database saved setting upon page load was casting it as a int?. So when I tried to use teh property bag setting object which held the setting it would sometimes work and sometimes fail because it would either be stored as a int? or a short? Inherited legacy code FTW! ARG! Code updated to do all conversions to and from db and settings as short? – RobDog888 Feb 25 '14 at 22:19