Reputation: 87
I have this code and it doesn't work for some reason. I don't understand it. What is wrong?
byte dog = (byte)2*byte.Parse("2");
I get this exception in LinqPad: "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)."
Also what is the right way to write this code? Thanks.
Upvotes: 3
Views: 2335
Reputation: 25581
Multiplying a byte value with another byte value will for most of the possible outcomes render a value that doesn't fit in a byte. The extreme case is the max value product 255 * 255 - while each factor fits in a byte, the product needs an integer to fit.
Upvotes: 2
Reputation: 26635
All arithmetic operations on sbyte, byte, ushort, and short are widened to int. For example, the third line will give compiler error:
byte b1 = 1;
byte b2 = 2;
byte b3 = (b1 * b2); // Exception, Cannot implicitly convert type 'int' to 'byte
byte b4 = (byte)(b1 * b2); // everything is fine
So, change your code as:
byte dog = (byte)((byte)2*byte.Parse("2"));
For more information: Look at this SO question
Upvotes: 2
Reputation: 28355
That's because, from compilator opinion, you're trying to cast to the byte
only first multiplier, not the whole result. This is because of operators precedence in c#
Try this:
byte dog = (byte) (2*byte.Parse("2"));
Also you should note that you can got an integer bigger than maximum byte
value (which is a const equal to 255
, and there will be a loss of data by such type conversion.
Upvotes: 0