I like to ask a wide variety of technical questions targeted to the candidate's seniority during interviews. My favorite C# question focuses on converting an Int64 into an Int32. Hopefully, this isn't something you need to perform often (poor design) but occasionally we have to clean up after the other guy, right? ;-) (If you interview with me and are reading this post-consider it a gimme...and hopefully you learned something anyway.)
Situation: We have an Int64 "b" I need to convert into an Int32 "a". How should we set a = b in the safest manner (i.e. no data loss)? Here are some options:
Many developers unknowingly choose Line 19. Bugs introduced with this code can be some of the nastiest to track down. Be safe out there! Convert explicitly using the Framework.
Good web links for conversion:
Jeff Adkin's Data Conversion posting
Explicit Numeric Conversions Table (C# Reference)
Situation: We have an Int64 "b" I need to convert into an Int32 "a". How should we set a = b in the safest manner (i.e. no data loss)? Here are some options:
- Line 15 does not compile throwing a "Cannot implicitly convert type 'long' to 'int'. " exception.
- Line 17 properly raises an OverflowException.
- Line 19 does _not_ throw an exception. a's value incorrectly becomes 1569325055.
- Line 21 properly raises an OverflowException.
Many developers unknowingly choose Line 19. Bugs introduced with this code can be some of the nastiest to track down. Be safe out there! Convert explicitly using the Framework.
Good web links for conversion:
Jeff Adkin's Data Conversion posting
Explicit Numeric Conversions Table (C# Reference)
Comments