Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Casting question 1

Status
Not open for further replies.

jasonp45

Programmer
Aug 23, 2001
212
US
I have a class property 'FileSize_MB_InitialFile', declared as Int16. When I set it like this it works:
Code:
this.FileSize_MB_InitialFile = Convert.ToInt16(fileInfo.Length);

But when I set it like this (since I want MB, not bytes), it throws an error:
Code:
this.FileSize_MB_InitialFile = Convert.ToInt16(fileInfo.Length) / 1000;

The error is "Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)"

Placing the division operation inside the parentheses works though:
Code:
this.FileSize_MB_InitialFile = Convert.ToInt16(fileInfo.Length / 1000);

I'm curious why it generates this error in the second instance.
 
A megabyte is 1024 kilobytes, not 1000. Very interesting find though
 
Thanks...I'm only approximating, but I'd rather have the approximation be closer! I'll adjust my divisor.
 
You'd think by now that HDD manufacturers would define KB, MB, and GB as factors of 1024. Once terabytes become the base size as GB are now, we'll "lose" even more of the harddrive to the decimal to binary conversion that operating systems perform
 
If you look at the language documentation, you'll see that the divison operator is defined on signed and unsigneds int (Int32) and long (Int64) types, but not on short (Int16). It takes 2 ints and returns an int. To do division on shorts, the compiler must implicitly convert them to ints. Incidentally, this means that the ToInt16() on the left operand of the division is completely pointless, as the compiler will just have to convert it back to an Int32 anyway.

The error comes up because your property is an Int16 and the division operator is returning an Int32. As the message suggests, C# can't implicitly convert an Int32 to an Int16 (probably because it could lead to data loss), so you need the explicit conversion on the result of the division that you had in the working version.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top